1

所以,我有一个名为“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()
4

2 回答 2

1

您可以使用订单对象的元对象来遍历字段。前任。

for field in order._meta.fields():
    if type(field) = django.db.models.fields.BooleanField:
       setattr(order, field.name, True)
于 2013-08-20T15:25:35.037 回答
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})
于 2013-08-20T04:48:25.687 回答