0

我正在使用tastepie来创建一个API,但我一直在尝试对某种类型的小数总和进行注释。每个事务都有一个关联的存储桶类型,我想按存储桶类型分组,并对事务求和。

api资源

class TransactionTotalResource(ModelResource):

    class Meta:
        queryset = TTransaction.objects.values('bucket').annotate(bucket_total=Sum('amount'))   
        resource_name = 'transaction_total'
        include_resource_uri = False
        allowed_methods = ['get']
        authorization= Authorization()

模型

class TTransaction(models.Model):
    bucket = models.ForeignKey(TBucket)
    date = models.DateField()
    transaction_type_id = models.IntegerField()
    amount = models.DecimalField(null=True, max_digits=18, decimal_places=2, blank=True)
    account_id = models.IntegerField()
    recurrence_flag = models.SmallIntegerField(null=True)
    notes = models.CharField(null=True,max_length=100)
    paid = models.SmallIntegerField(null=True)
    is_credit = models.SmallIntegerField(null=True)
    reconciled = models.SmallIntegerField(null=True)
    active = models.SmallIntegerField()
    class Meta:
        db_table = u't_transaction'
        ordering = ['-date']

如果我从终端运行它,它可以工作。

from django.db.models import Sum
TTransaction.objects.values('bucket').annotate(bucket_total=Sum('amount'))

[{'bucket': 10, 'bucket_total': Decimal('35.24')}, {'bucket': 2, 'bucket_total': Decimal('62.00')}]

但是,为此点击 transaction_total URL,我得到了

{"error": "The object '{'bucket': 10, 'bucket_total': Decimal('35.24')}' has an empty attribute 'account_id' and doesn't allow a default or null value."}

如果我将所有模型字段设置为“null=True”,那么我会得到一个不同的错误:

{"error_message": "invalid literal for int() with base 10: ''", "traceback" ...

有没有办法让美味派与注释一起工作?

4

1 回答 1

0

以为我会回答这个问题,因为我在脱水方法中找到了一种方法:

def dehydrate(self, bundle):
    transaction = TTransaction.objects.filter(bucket_id=bundle.data['id']).values('bucket').order_by('bucket').annotate(Sum('amount'))
    bundle.data['transaction_total'] = transaction
    return bundle
于 2013-05-14T17:17:15.840 回答