[英]Reference two foreign keys in Django data model
I want to reference two foreign keys in the Conversation model, because user_one and user_two can be a Person or Business either way.我想在 Conversation 模型中引用两个外键,因为 user_one 和 user_two 可以是个人或企业。 What is the best way of expressing this?
表达这一点的最佳方式是什么?
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)
I would probably use django model inheratance and create an Entity model.我可能会使用django 模型继承并创建一个实体模型。
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')
Note that due to the use of GenericForeignKey
filtering will not work the traditional way.请注意,由于使用了
GenericForeignKey
过滤,因此传统方式将不起作用。 Then you'll be able to do something like this:然后你就可以做这样的事情:
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)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.