我有这个代码在我的views.py
:
from django.shortcuts import render
from .helpers import *
from .forms import OrderForm
def create_order(request):
if request.method == 'POST':
form = OrderForm(request.POST)
if not request.POST._mutable:
request.POST._mutable = True
if form.is_valid():
obj = form.save(commit=False)
obj.total_price = calculate_total_price_obj(obj)
obj.save()
else:
form = OrderForm()
return render(request, 'create_order.html', {'form': form})
我有这个在我的helpers.py
:
def calculate_total_price_obj(obj) -> float:
"""
Calculate the total_price of the order.
This function has to be called after the Order has been created and saved.
"""
prices_of_ordered_foods = obj.ordered_foods
print(prices_of_ordered_foods)
return sum(prices_of_ordered_foods)
我想要实现的是:
- 获取用户发送的表单
- 根据用户填写表格时选择的膳食/食品的价格计算字段
total_price
(这是我的models.py
中的ManyToManyField)。计算完成后,保存表单。(计算为简单的sum()
方法)
然而,这不起作用。我得到这个错误:<MyOrderObject> needs to have a value for field "id" before this many-to-many relationship can be used.
有什么好办法吗?
谢谢
不能用Order.save
发出的post_save
信号来计算total_price
,因为只有在调用save
方法之后才会设置多对多关系。因此,您需要保存Order实例,分配膳食/食物,然后才调用calculate_total_price_obj
。
def create_order(request):
if request.method == 'POST':
form = OrderForm(request.POST)
if not request.POST._mutable:
request.POST._mutable = True
if form.is_valid():
obj = form.save(commit=True)
# Note that you must set many-to-many relationships before calling calculate_total_price_obj
obj.total_price = calculate_total_price_obj(obj)
obj.save()
else:
form = OrderForm()
return render(request, 'create_order.html', {'form': form})