Модель Django - вычисление поля при сохранении не работает
Вот такая модель у меня есть:
class Order(models.Model):
"""
Model for orders
"""
order_statuses = [
("PR", "Accepted"), # The default status has to be the first (with index = 0)
("PS", "Status 1"),
("VY", "Status 2"),
("ZR", "Status 3"),
("OK", "Status 4")
]
customer_name = models.CharField(max_length=255)
customer_email = models.EmailField(blank=True)
ordered_foods = models.ManyToManyField(Food)
table = ForeignKey(Table, on_delete=CASCADE)
status = models.CharField(choices=order_statuses,
default=order_statuses[0],
max_length=2)
total_price = models.FloatField(editable=False, default=0)
def save(self, *args, **kwargs) -> None:
"""
This calculates the total_price of the created order
"""
if not self.id:
super(Order, self).save(*args, **kwargs)
self.total_price = self.calculate_total_price
super(Order, self).save(*args, **kwargs)
@property
def calculate_total_price(self) -> float:
print('Total price:', self.total_price)
print('All prices of the foods in order:', self.ordered_foods.values_list('price', flat=True))
total_price = 0
for ordered_food in self.ordered_foods.values_list('price', flat=True):
total_price += ordered_food
print('Price ordered food:', ordered_food)
print('Total price:', total_price)
return total_price
def __str__(self) -> str:
return f"{self.id} / {self.customer_name} / {self.table.name} {self.table.number} / STATUS: {self.status} / {self.total_price}"
What I'm trying to achieve is, that the total_price
of my Order
model will get immediately calculated after a user clicks the Save button.
The code I pasted above works only if I create the Order (after which the total_price
is 0) and then I just re-save it again. However, this does not work on the initial save. So, if I create the order right now, the total_price
field will not get calculated on the first time I click save. If I click the Save button again (now for the already existent Order), it will calculate it properly.
Вот вывод из терминала (здесь есть несколько операторов print()
, которые, возможно, помогут вам разобраться, в чем здесь дело):
# This is the output from when I created the Order (first time clicking Save button)
Total price: 0
All prices of the foods in order: <QuerySet []>
Total price: 0
[30/Aug/2021 10:02:49] "POST /admin/backoffice/order/add/ HTTP/1.1" 302 0
[30/Aug/2021 10:02:49] "GET /admin/backoffice/order/ HTTP/1.1" 200 9508
[30/Aug/2021 10:02:49] "GET /static/admin/js/nav_sidebar.js HTTP/1.1" 304 0
[30/Aug/2021 10:02:49] "GET /static/admin/js/jquery.init.js HTTP/1.1" 304 0
[30/Aug/2021 10:02:49] "GET /static/admin/js/vendor/jquery/jquery.js HTTP/1.1" 304 0
[30/Aug/2021 10:02:49] "GET /static/admin/js/urlify.js HTTP/1.1" 304 0
[30/Aug/2021 10:02:49] "GET /static/admin/js/core.js HTTP/1.1" 304 0
[30/Aug/2021 10:02:49] "GET /static/admin/js/admin/RelatedObjectLookups.js HTTP/1.1" 304 0
[30/Aug/2021 10:02:49] "GET /static/admin/js/prepopulate.js HTTP/1.1" 304 0
[30/Aug/2021 10:02:49] "GET /static/admin/js/vendor/xregexp/xregexp.js HTTP/1.1" 304 0
[30/Aug/2021 10:02:49] "GET /static/admin/js/actions.js HTTP/1.1" 304 0
[30/Aug/2021 10:02:49] "GET /admin/jsi18n/ HTTP/1.1" 200 3195
[30/Aug/2021 10:02:49] "GET /static/admin/img/icon-yes.svg HTTP/1.1" 304 0
[30/Aug/2021 10:02:49] "GET /static/admin/fonts/Roboto-Regular-webfont.woff HTTP/1.1" 304 0
[30/Aug/2021 10:02:49] "GET /static/admin/fonts/Roboto-Light-webfont.woff HTTP/1.1" 304 0
[30/Aug/2021 10:02:49] "GET /static/admin/fonts/Roboto-Bold-webfont.woff HTTP/1.1" 304 0
[30/Aug/2021 10:02:59] "GET /admin/backoffice/order/10/change/ HTTP/1.1" 200 10417
[30/Aug/2021 10:02:59] "GET /static/admin/js/prepopulate_init.js HTTP/1.1" 304 0
[30/Aug/2021 10:02:59] "GET /static/admin/js/change_form.js HTTP/1.1" 304 0
[30/Aug/2021 10:02:59] "GET /admin/jsi18n/ HTTP/1.1" 200 3195
[30/Aug/2021 10:02:59] "GET /static/admin/css/forms.css HTTP/1.1" 304 0
[30/Aug/2021 10:02:59] "GET /static/admin/img/icon-changelink.svg HTTP/1.1" 304 0
[30/Aug/2021 10:02:59] "GET /static/admin/css/widgets.css HTTP/1.1" 304 0
# This is the output from when I just "updated" the Order (second time clicking Save button without modifying any fields, of course)
Total price: 0.0
All prices of the foods in order: <QuerySet [5.69]>
Price ordered food: 5.69
Total price: 5.69
[30/Aug/2021 10:03:02] "POST /admin/backoffice/order/10/change/ HTTP/1.1" 302 0
[30/Aug/2021 10:03:02] "GET /admin/backoffice/order/ HTTP/1.1" 200 9514
[30/Aug/2021 10:03:02] "GET /admin/jsi18n/ HTTP/1.1" 200 3195
Оцените вашу помощь.
Большое спасибо.