在Django项目中,我的模型定义如下:
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
在项目中,我可以这样使用它们:
folder = Folder.objects.get(name="fooo")
for f in folder.files.iterator():
print f.name
我现在正准备使用South
进行数据迁移,我需要在其中访问文件夹的文件,但代码folder.files.iterator()
给了我一个错误:
Error in migration: main:0015_contenttype_to_manytomany_step0
AttributeError: 'Folder' object has no attribute 'files'
预期吗?
我怎么知道文件属于文件夹?
答案 0 :(得分:2)
我找到了一个解决方法,使用适当的content_type_id和object_id过滤File的对象:
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():
# ...
这有效,但可读性较差。