我有 3 个独立的模型
1. InitialBills
id uuid
name varchar
2. CurrentBills
id uuid
name varchar
3. BillPaymentInfo
id uuid
name varchar
现在我还有另一张表,即文档附件表
BillPaymentDocument
id uuid
biil_data FK [ models either from InitialBills, currentBill or BillPaymentInfo ]
doc_name varchar
doc_type choice field
I want it to be like
BillPaymentDocument
project = models.ForeignKey(InitialBills,currentBill,BillPaymentInfo on_delete=models.SET_NULL, blank=False, null=True,
related_name='bill_payment_detail')
我不想为此提供单独的表格,我该怎么做???
在 Django 中,您可以使用 通用外键 将一个表与多个表之一相关联。
from django.db import models
from django.contrib.contenttypes.fields import GenericForeignKey, GenericRelation
from django.contrib.contenttypes.models import ContentType
class InitialBills(models.Model):
uuid = models.AutoField(primary_key=True)
name = models.CharField(max_length=255)
class CurrentBills(models.Model):
uuid = models.AutoField(primary_key=True)
name = models.CharField(max_length=255)
class BillPaymentInfo(models.Model):
uuid = models.AutoField(primary_key=True)
name = models.CharField(max_length=255)
class BillPaymentDocument(models.Model):
uuid = models.AutoField(primary_key=True)
# content_type tells Django which model this object will link to
content_type = models.ForeignKey(
ContentType,
limit_choices_to = {
"model__in": ('InitialBills', 'CurrentBills', 'BillPaymentInfo')
},
on_delete=models.CASCADE
)
# object_id is the id of the object in the linked model
object_id = models.PositiveIntegerField(null=False)
# this is the actual foreign key object itself, rather than the id
project = GenericForeignKey("content_type", "object_id")
# ... then add some more fields if you wish ...
document_name = models.CharField(max_length=255)
# Now you need to add the relation manually onto the FK'ed models,
# as Django doesn't do this for you,
# in case you ever want to query this relationship backwards
InitialBills.add_to_class("bill_payment_documents", GenericRelation('BillPaymentDocument', content_type_field='content_type', object_id_field='object_id'))
CurrentBills.add_to_class("bill_payment_documents", GenericRelation('BillPaymentDocument', content_type_field='content_type', object_id_field='object_id'))
BillPaymentInfo.add_to_class("bill_payment_documents", GenericRelation('BillPaymentDocument', content_type_field='content_type', object_id_field='object_id'))
content_type
和object_id
字段更多供Django内部使用。您最常在代码中引用 content_object
,因为这相当于此用例的 ForeignKey
字段。