单个tastypie资源中的多个模型

时间:2012-10-04 14:09:10

标签: django tastypie

我想制作一个单一的tastypie资源,它返回两个不同模型的公共字段。

我的模型描述如下:

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()

由于字段名称不直接匹配,我需要一种方法将Model字段映射到Resource字段。例如,资源ID字段将是发票的invoice_number和付款的payment_id。

最好的方法是什么?

1 个答案:

答案 0 :(得分:1)

如果您不想从ModelResource继承,可以使用脱水方法添加其他值:

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()

    # Add values in dehydrate
    def dehydrate(self, bundle):
        bundle.data['some_invoide_value'] = invoice.value
        bundle.data['some_payment_value'] = payment.value
        return super(TransactionResource, self).dehydrate(bundle)
相关问题