本文介绍了Django GenericRelation字段在South迁移期间不可用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
在Django项目中,我有如下定义的模型:
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
我正在准备一个具有 South 其中我需要访问文件夹的文件,但代码
folder.files.iterator()
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()
给我一个错误:
Error in migration: main:0015_contenttype_to_manytomany_step0
AttributeError: 'Folder' object has no attribute 'files'
是否预期?
我如何知道文件是文件夹的一部分?
How can I know the files being part of a folder?
推荐答案
我找到了一个解决方法过滤File的对象,具有适当的content_type_id和object_id:
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.
这篇关于Django GenericRelation字段在South迁移期间不可用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!