【问题标题】:Tastypie annotation error "empty attribute..."Tastypie 注释错误“空属性...”
【发布时间】:2013-05-09 02:49:08
【问题描述】:

我正在使用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" ...

有没有办法让 sweetpie 与注释一起工作?

【问题讨论】:

    标签: python django tastypie


    【解决方案1】:

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

    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
    

    【讨论】:

      猜你喜欢
      • 2014-10-26
      • 1970-01-01
      • 1970-01-01
      • 2016-07-22
      • 1970-01-01
      • 2012-07-02
      • 2012-09-09
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多