Django 单个tastypie资源中的多个模型

Django 单个tastypie资源中的多个模型,django,tastypie,Django,Tastypie,我想创建一个tastype资源,它返回来自两个不同模型的公共字段 我有这样描述的模型: Class Invoice(models.Model): transaction_batch = models.ForeignKey(TransactionBatch) invoice_number = models.IntegerField() subtotal = models.DecimalField(max_digits=20, decimal_places=2) ta

我想创建一个tastype资源,它返回来自两个不同模型的公共字段

我有这样描述的模型:

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字段将是发票的发票号和付款的付款ID


最好的方法是什么?

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

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)

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

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)