【问题标题】:how can i solve this error ( Field 'total_price' expected a number but got {'price__sum': 222} ) django? [duplicate]我该如何解决这个错误(字段'total_price'期望一个数字但得到{'price__sum':222})django? [复制]
【发布时间】:2020-08-29 18:28:32
【问题描述】:

如何获得用户在商店中添加的书籍的总价格。我还添加了@property 来计算并保存总价。当我尝试保存表单时,我收到 typeError Exception Value: Field 'total_price' expected a number but got {'price__sum': 222}.

我该如何解决这个问题?

商店

class Book(models.Model):
    name = models.CharField(max_length=100)
    price = models.IntegerField(default=0)

    def __str__(self):
        return self.name


class Store(models.Model):
    keeper = models.ForeignKey(User, on_delete=models.SET_NULL, null=True)
    books = models.ManyToManyField(Book)
    total_price = models.IntegerField(default=0)

    @property
    def save(self):
        self.total_price = self.books.all().aggregate(Sum('price'))
        super(Store, self).save()

【问题讨论】:

    标签: django django-models django-views


    【解决方案1】:

    聚合返回字典所以

       if self.pk:
            self.total_price = self.books.all().aggregate(Sum('price'))['price__sum']
    

    同样保存方法不需要@property装饰器


    编辑:

    这是多对多的关系,这意味着更好的想法是使用 post_clear 跟踪 m2m_changed 信号并更改 total_price 您也可以看到这将是一项乏味的工作,因为您仍然需要检查书籍是否改变了价格通过覆盖 Book 模型的 save() 方法


    我不建议您使用 total_price 字段,因为您始终可以在查询中使用 annotate 这个计数,将作业留给数据库,因为它是为此类任务而制作的

    【讨论】:

    • 现在这个警报"<Store: Store object (None)>" needs to have a value for field "id" before this many-to-many relationship can be used.
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2011-09-04
    • 2018-03-09
    • 1970-01-01
    • 2021-09-19
    • 2022-12-12
    • 2022-11-11
    • 1970-01-01
    相关资源
    最近更新 更多