"Tastypie注释错误 空属性..."

2024-09-28 20:17:28 发布

您现在位置:Python中文网/ 问答频道 /正文

我使用Tastype创建一个API,但我一直在试图注释某个类型上小数的总和。每个事务都有一个关联的bucket类型,我想按bucket类型分组,并求和事务。在

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

型号

^{pr2}$

如果我从终端运行它,它能工作。在

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')}]

但是,点击这个事务的总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" ...

有什么方法可以用注释来工作?在


Tags: 类型objectsbucketerror事务amountnullresource
1条回答
网友
1楼 · 发布于 2024-09-28 20:17:28

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

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

相关问题 更多 >