我正在使用tastypie创建一个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网址,我得到了
{"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" ...
有没有办法让tastypie与annotaion一起工作?
答案 0 :(得分: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