问题
In a Django project, I have models defined like this :
from django.db import models
from django.contrib.contenttypes.models import ContentType
from django.contrib.contenttypes import generic
class TaggedEntry(models.Model):
content_type = models.ForeignKey(ContentType)
object_id = models.PositiveIntegerField()
content_object = generic.GenericForeignKey("content_type", "object_id")
class Meta:
abstract = True
class File(TaggedEntry):
name = models.CharField(max_length = 256)
# some more fields
class Folder(models.Model):
name = models.CharField(max_length = 200)
files = generic.GenericRelation(File)
# some more fields
In the project I can use them this way :
folder = Folder.objects.get(name="fooo")
for f in folder.files.iterator():
print f.name
I'm now preparing a datamigration with South
in which I need to access the files of the folders but the code folder.files.iterator()
gives me an error :
Error in migration: main:0015_contenttype_to_manytomany_step0
AttributeError: 'Folder' object has no attribute 'files'
Is it expected?
How can I know the files being part of a folder?
回答1:
I've found a workaround filtering File's object with the appropriate content_type_id and object_id:
from django.contrib.contenttypes.models import ContentType
# ...
folder_contenttype = ContentType.objects.get(name="folder")
for folder in orm.Folder.objects.all():
for f in orm.File.objects.filter(content_type_id = folder_contenttype.id, object_id = folder.id): # replaces folder.files.iterator():
# ...
This works but is less readable.
来源:https://stackoverflow.com/questions/21759146/django-genericrelation-fields-not-available-during-south-migration