我使用django模型继承来创建实体模型,因此我可以在Conversation模型中引用两个外键,因为entity_1和entity_2可以是Person或Business。但是,我不断收到以下错误消息:
api.Conversation.entity_1: (fields.E300) Field defines a relation with model 'Entity', which is either not installed, or is abstract.
api.Conversation.entity_2: (fields.E300) Field defines a relation with model 'Entity', which is either not installed, or is abstract.
到目前为止,这是我的代码:
class Entity(models.Model):
id = models.UUIDField(primary_key=True, default=uuid4, editable=False)
class Meta:
abstract = True
class Person(Entity):
"""
Person model
"""
avatar = models.ImageField(upload_to=get_upload_avatar_path, blank=True, null=True, default=None, max_length=255)
first_name = models.CharField(max_length=255)
last_name = models.CharField(max_length=255)
class Business(Entity):
"""
Business model
` """
name = models.CharField(max_length=255, null=True, default=None)
class Conversation(models.Model):
id = models.UUIDField(primary_key=True, default=uuid4, editable=False)
entity_1 = models.ForeignKey(Entity)
entity_2 = models.ForeignKey(Entity)
答案 0 :(得分:3)
你不能引用抽象类。它不会创建数据库表。 https://docs.djangoproject.com/en/1.9/topics/db/models/#abstract-base-classes
您可以使用GenericForeignKey https://docs.djangoproject.com/en/1.9/ref/contrib/contenttypes/#generic-relations
一个例子:
from django.contrib.contenttypes.fields import GenericForeignKey
from django.contrib.contenttypes.models import ContentType
class Conversation(models.Model):
entity_one = models.ForeignKey(ContentType,on_delete=models.CASCADE,related_name='entity_one')
entity_two = models.ForeignKey(ContentType,on_delete=models.CASCADE,related_name='entity_two')
entity1_id = models.PositiveIntegerField()
entity2_id = models.PositiveIntegerField()
entity_1_object = GenericForeignKey('entity_one', 'entity1_id')
entity_2_object = GenericForeignKey('entity_two', 'entity2_id')