所以,我有一个名为“order”的表,它有一个带有“store”表的外键。订单表的布尔字段默认设置为false。创建新订单时,我需要遍历与每个单独商店关联的布尔值,并将其他订单设置为false,将新订单设置为true。不知道如何为此创建for循环。首先我尝试将其设置为视图,但也许它可以放入forms.py文件中?这是我到目前为止的创建代码。
def create(request):
if request.POST:
form = OrderForm(request.POST)
if form.is_valid():
form.save()
return HttpResponseRedirect('/liquors/all')
else:
form = OrderForm()
args = {}
args.update(csrf(request))
args['form'] = form
return render_to_response('create_order.html', args)
根据要求提供的模型,除订单模型外,您不需要任何其他内容:
class Order(models.Model):
OrderID = models.AutoField(primary_key=True)
storeID = models.ForeignKey(Store)
DateCreated = models.DateField('Date Created', auto_now_add=True)
OrderName = models.CharField('Order Name', max_length=25 )
Active = models.BooleanField()
答案 0 :(得分:1)
你必须return render_to_response('create_order.html', args)
一个缩进。这样验证表格不会受到影响。如果您使用的是csrf request
,则无需使用render
。 I think there is no need to use OrderId in Order model, since it is automattically created. ie id
from django.shortcuts import render
from <appname>.models import Order,Store
def create(request):
if request.POST:
form = OrderForm(request.POST)
if form.is_valid():
#i just assume the storeid variable is exist in request.POST and it is ID.
store_data=Store.objects.get(id=request.POST['storeid'])
#here you might need to update the other orderform to false
Order.objects.filter(storeID=store_data).update(Active=False)
fo=Order(storeID=store_data,Active=True)
frm_order=OrderForm(request.POST,instance=fo)
frm_order.save()
return HttpResponseRedirect('/liquors/all')
else:
form = OrderForm()
return render(request,'create_order.html', {'form':form})
答案 1 :(得分:1)
您可以使用订单对象的元对象循环遍历字段。实施例
for field in order._meta.fields():
if type(field) = django.db.models.fields.BooleanField:
setattr(order, field.name, True)