gpt4 book ai didi

python - 引用Django数据模型中的两个外键

转载 作者:太空宇宙 更新时间:2023-11-03 16:37:41 24 4
gpt4 key购买 nike

我想在对话模型中引用两个外键,因为 user_one 和 user_two 可以是个人或企业。表达这一点的最佳方式是什么?

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)

最佳答案

我可能会使用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)

关于python - 引用Django数据模型中的两个外键,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37082169/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com