我想制作一个从两个不同模型返回公共字段的美味资源。
我有这样描述的模型:
Class Invoice(models.Model):
transaction_batch = models.ForeignKey(TransactionBatch)
invoice_number = models.IntegerField()
subtotal = models.DecimalField(max_digits=20, decimal_places=2)
tax = models.DecimalField(max_digits=20, decimal_places=2)
total = models.DecimalField(max_digits=20, decimal_places=2)
location = models.ForeignKey(Delivery_location)
date_time = models.DateTimeField()
Class Payment(models.Model):
transaction_batch = models.ForeignKey(TransactionBatch)
location = models.ForeignKey(Delivery_location)
payment_id = models.IntegerField(pk=True)
datetime = models.DateTimeField()
amount = models.DecimalField(max_digits=20, decimal_places=2)
payment_method = models.IntegerField(choices = PAYMENT_METHOD_CHOICES)
并希望制作具有以下字段的资源:
Class TransactionResource(Resource):
type = fields.CharField() #"invoice" or "payment"
id = fields.CharField(attribute='name') #invoice_number or payment_id
location = fields.ForeignKey(LocationResource)
total = fields.IntegerField(attribute='total', null=True) #total or amount
datetime = fields.DateField()
由于字段名称不直接匹配,我需要一种将模型字段映射到资源字段的方法。例如,资源 ID 字段将为 Invoices 的 invoice_number 和 Payments 的 payment_id。
解决这个问题的最佳方法是什么?