在Django数据模型中引用两个外键

时间:2016-05-06 22:12:52

标签: python django

我想在Conversation模型中引用两个外键,因为user_one和user_two可以是Person或Business。表达这个的最佳方式是什么?

class Person(models.Model):
    """
    Person model
    """
    id = models.UUIDField(primary_key=True, default=uuid4, editable=False)
    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(models.Model):
    """
    Business model
`   """
    id = models.UUIDField(primary_key=True, default=uuid4, editable=False)
    name = models.CharField(max_length=255, null=True, default=None)


class Conversation(models.Model):
    """
    Conversation model
    Contains conversation relational data between registered users
    """
    id = models.UUIDField(primary_key=True, default=uuid4, editable=False)
    #user_one = models.ForeignKey(Person, null=True, default=None)
    #user_two = models.ForeignKey(Business, null=True, default=None)


class ConversationReply(models.Model):
    """
    Conversation reply model
    Contains conversation reply data
    """
    id = models.UUIDField(primary_key=True, default=uuid4, editable=False)
    date_time = models.DateTimeField(blank=True, null=True, default=None)
    conversation = models.ForeignKey(Conversation, null=True, default=None)
    reply = models.CharField(max_length=255)

1 个答案:

答案 0 :(得分:1)

我可能会使用django model inheratance并创建一个实体模型。

 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)
    content_object_1 = GenericForeignKey('content_type', 'object_1_id')
    content_object_2 = GenericForeignKey('content_type', 'object_2_id')

请注意,由于使用GenericForeignKey过滤将无法采用传统方式。然后你就可以做到这样的事情:

from django.contrib.contenttypes.models import ContentType

contenttype_obj = ContentType.objects.get_for_model(person_object)

Conversation.objects.filter(object_id_1=person_object.id, content_type=contenttype_obj)