我有两个模型想要加入,但它们没有任何外键
class Invoice(models.Model):
invoice_id = models.IntegerField(blank=True, null=True)
quotation_id = models.IntegerField(blank=True, null=True)
client_id = models.ForeignKey(tbl_customer, on_delete=models.CASCADE)
invoice_number = models.IntegerField(blank=True, null=True)
quotation_number = models.IntegerField(blank=True, null=True)
date = models.DateField(blank=True, null=True)
total_amount = models.DecimalField(max_digits=8, decimal_places=2, blank=True, null=True)
total_tax = models.DecimalField(max_digits=8, decimal_places=2, blank=True, null=True)
document_type = models.CharField(max_length=50, default='', blank=True, null=True)
和
class Invoice_Description(models.Model):
invoice_id = models.IntegerField(blank=True, null=True)
client_id = models.ForeignKey(tbl_customer, on_delete=models.CASCADE)
quotation_id = models.IntegerField(blank=True, null=True)
item_id = models.ForeignKey(tbl_item, on_delete=models.CASCADE)
item_qty = models.DecimalField(max_digits=8, decimal_places=2, blank=True, null=True)
item_unit_price = models.DecimalField(max_digits=8, decimal_places=2, blank=True, null=True)
Invoice
包含有关发票凭证、其总价、日期等的信息,而Invoice_Description
则保存特定发票上添加的项目、项目价格、总数量、每个项目的折扣等的记录。
我想在报告中显示与等项目有关的所有记录
ITEM NAME CUSTOMER NAME INV. NO. QTY DOCUMENT TYPE UNIT PRICE SALE PRICE
Item1 Client1 01 950.00 1000.00
除了Invoice
模型中的INV. NO.
和DOCUMENT TYPE
之外,我拥有Invoice_Description
中所有可用的列。
在这种情况下,我不想使用ForeignKey,因为这些模型已经在很多地方使用了,更改数据库需要到处更改。
我的问题是,我想在Django中加入两个模型,但没有ForeignKey,这样我就可以得到相应行的Invoice No.和Document Type。
有什么关于我该怎么做的想法吗??
如果您只想检索属于给定Invoice
的InvoiceDescription
对象,则可以执行以下操作:
invoice = Invoice.objects.first()
try:
description = InvoiceDescription.objects.get(invoice_id=invoice.invoice_id)
except InvoiceDescription.DoesNotExist:
description = None
我假设字段invoice_id
指的是发票ID。虽然您没有使用models.ForeignKey
声明它,但在这种情况下,它仍然充当外键。您只需要手动查找即可。