我有一个抽象模型,从中继承了我的几个主要模型。在这种情况下,主要困难是我需要参考相同的模型,比如 a ForeignKey
to self
。我已经读过抽象模型ForeignKey
中不可能并且可以提供帮助,但是我不能真正使它起作用。GenericForeignKey
据我了解,结构应该如下所示:
class BaseModel(models.Model):
versions = GenericRelation('self')
date_created = models.DateTimeField(default=datetime.datetime.now)
is_deleted = models.BooleanField(default=False)
content_type = models.ForeignKey(ContentType, blank=True, null=True)
object_id = models.PositiveIntegerField(blank=True, null=True)
content_object = GenericForeignKey('content_type', 'object_id')
class FirstModel(BaseModel):
some_fields...
class AnotherModel(BaseModel):
another_fields...
但是用这种方法我得到一个错误:
>>> item1 = FirstModel.objects.get(id=1)
>>> item2 = FirstModel.objects.get(id=2)
>>> item2.content_object = item1
Traceback (most recent call last):
File "<input>", line 1, in <module>
File "/home/michael/.virtualenvs/diagspecgen/lib/python3.6/site-packages/django/contrib/contenttypes/fields.py", line 245, in __set__
ct = self.get_content_type(obj=value)
File "/home/michael/.virtualenvs/diagspecgen/lib/python3.6/site-packages/django/contrib/contenttypes/fields.py", line 163, in get_content_type
return ContentType.objects.db_manager(obj._state.db).get_for_model(
AttributeError: 'ReverseGenericRelatedObjectsDescriptor' object has no attribute '_state'
我试图达到的目标是绝对不可能的,唯一的解决方案是在现有模型中显式创建所需的字段吗?