python-向南迁移期间Django GenericRelation字段不可用
作者:互联网
在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'
是预期的吗?
我怎么知道文件是文件夹的一部分?
解决方法:
我找到了一种解决方法,使用适当的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():
# ...
这可行,但可读性较差.
标签:python,django,django-south 来源: https://codeday.me/bug/20191012/1900608.html