Django-覆盖保存方法 [英] Django - override save method

查看:42
本文介绍了Django-覆盖保存方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在为Django中的模型覆盖 save()方法,但无法正常工作.

I'm overriding the save() method for a model in Django, but it's not working properly.

我希望 book_quantity 每次在编辑购物车中的书本数量并单击保存"按钮时自动更新.

I want the book_quantity to update automatically each time when, I edit the number of books in a cart and click save button.

例如:

我已经将书的编号从0更改为11,然后单击保存"按钮,但是 book_quantity 仍然显示数字0(先前的数字).如果我将数字从11更改为22或不更改数字,请再次单击保存按钮. book_quantity 将为11.因此,它始终显示前一个数字.但是我想要的是,每当我单击一次保存"按钮时, book_quantity 都会立即更改为正确的数字.

I've already changed the number of the book from 0 to 11 and clicked the save button, but the book_quantity still showing number 0 (the previous number). If I change the number from 11 to 22 or not change the number then click the save button again. The book_quantity will be 11. So it always shows the previous number. But what I want is that the book_quantity changes to the correct number immediately each time when I click the save button (once).

购物车/模型.py

class Cart(models.Model):
    user = models.OneToOneField(User, on_delete=models.CASCADE, null=True)
    book_quantity = models.IntegerField(default=0)
    total_price = models.DecimalField(max_digits=10, decimal_places=2, default=0)

    def __str__(self):
        return self.user.email + '_cart'

    def save(self, *args, **kwargs):
        self.book_quantity = 0
        books = BooksInCart.objects.filter(cart__user=self.user).values('quantity')
        for i in range(len(books)):
            self.book_quantity += books[i].get('quantity')
        super().save(*args, **kwargs)


class BooksInCart(models.Model):

    cart = models.ForeignKey(Cart, on_delete=models.CASCADE)
    book = models.ForeignKey(Book, on_delete=models.CASCADE)
    quantity = models.IntegerField(default=1)


    def __str__(self):
        return self.book.title

为什么要这样做,因为每次将 BooksInCart 实例添加到购物车中时,我都希望 book_quantity total_price 进行更新,或者从购物车中编辑/删除 BooksInCart .但是扩展 save()方法是我想到的唯一想法.还有其他更好的方法可以实现这一目标吗?

Why am I doing this it because I want the book_quantityand total_price update each time when I add a BooksInCart instance into the cart or edit/delete a BooksInCart from the cart. But extending the save() method is the only idea I came up with. Is there any other better way to achieve this?

推荐答案

好吧,我不确定您的想法,但是

Well, I not sure about your idea but,

也许您可以尝试使用信号?每次更改数量时,它都会更改book_quantity.如:

maybe you can try to use signal? everytime when your quantity is changed, it will change the book_quantity. Such as:

from django.db.models.signals import post_save

@receiver(post_save, sender=BooksInCart) # the sender is your fix
def update_book_quantity(sender, instance, **kwargs):
    book_quantity = 0
    books = BooksInCart.objects.filter(cart=instance.cart).values('quantity')
    for item in book.iterator():
        book_quantity += item.get('quantity')
    instance.update(book_quantity=book_quantity)
    # TODO

与此同时,我同意不需要将这些内容存储在数据库中.

坦率地说,这种设计太糟糕了,当服务被很多人使用时会出现问题.

Frankly speaking, this design is awful and it will case problem when the service is used by many people.

那么为什么不尝试将其保存在缓存中(也许尝试)或尝试另一种设计方案呢?

So why not try saving it in cache (try it maybe) or try another solution of your design?

这篇关于Django-覆盖保存方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆