Django 在抽象模型中引用相同的模型实例

Django refering to same model instances in Abstract Model

我有一个抽象模型,我的几个主要模型都继承自该模型。这种情况下的主要困难是我需要参考相同的模型,例如 ForeignKeyself。我读到 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'

我试图达到的是绝对不可能的,唯一的解决方案是在现有模型中明确创建所需的字段吗?

我试图在抽象模型上用 ForeignKey 复制你的问题,但它似乎适用于 Django 版本 1.11.1:

class BaseModel(models.Model):
    other = models.ForeignKey('self', null=True, blank=True)

    class Meta:
        abstract = True

class FirstModel(BaseModel):
    pass

class AnotherModel(BaseModel):
    pass

使用模型:

>>> fm1 = FirstModel.objects.create()
>>> fm2 = FirstModel.objects.create()
>>>
>>> fm1.other = fm2
>>> fm1.save()

以下对 other 的赋值会导致错误:

>>> am = AnotherModel.objects.create()
>>> am.other = fm1
ValueError: Cannot assign "<FirstModel: FirstModel object>": "AnotherModel.other" must be a "AnotherModel" instance.