【问题标题】:Multiple models in a single tastypie resource单一美味派资源中的多个模型
【发布时间】:2012-09-25 14:24:33
【问题描述】:

我想制作一个从两个不同模型返回公共字段的美味派资源。

我有这样描述的模型:

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。

最好的方法是什么?

【问题讨论】:

    标签: django tastypie


    【解决方案1】:

    如果不想从 ModelResource 继承,可以使用 dehydrate 方法添加附加值:

    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)
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2012-09-13
      • 2013-04-26
      • 2012-04-03
      • 1970-01-01
      • 1970-01-01
      • 2012-08-09
      • 1970-01-01
      相关资源
      最近更新 更多