如何根据Django中的ID保存所选数据

时间:2019-05-11 06:58:58

标签: django database updates id

我是新手。我想根据ID(OrderId)更新数据库中的数据(food_status),并将其保存到food_status列。

但是,它显示了一个错误

food_status.save(update_fields=['food_status'])
AttributeError: 'str' object has no attribute 'save'

models.py

class OrderItem(models.Model):
     Table_No = models.IntegerField(blank=False)
     FoodId = models.TextField()
     Item = models.TextField()
     Qty = models.IntegerField(blank=False)
     Price = models.TextField()
     Note = models.TextField(max_length=100, null=True)
     OrderId = models.TextField(max_length=100, null=True)

     FoodStatus = (
         ('1', 'Has been ordered'),
         ('2', 'cooked'),
         ('3', 'ready to be served'),
         ('4', 'done'),
     )
    food_status = models.CharField(max_length=50, choices=FoodStatus, 
                  default="has been ordered")

views.py

  def kitchen_view(request):
     chef_view = OrderItem.objects.all()
     if request.method == "POST":
         status = OrderItem.objects.filter(OrderId=['OrderId'])
         food_status = request.POST.get("food_status")
         status.food_status = food_status
         food_status.save(update_fields=['food_status'])
     return render(request, 'restaurants/kitchen_page.html', 
        {'chef_view':chef_view})

kitchen_page.html

   <form action="#" method="post">
    {% csrf_token %}
    {% for order in chef_view %}
        <table width="800">
            <tr>
                <th width="800">Table Number</th>
                <th width="800">Item</th>
                <th width="800">Quantity</th>
                <th width="800">Price</th>
                <th width="800">Note</th>
                <th width="800">Order Id</th>
                <th width="800">Status</th>
            </tr>
            <tr>
                <td width="800">{{ order.Table_No }}</td>
                <td width="800">{{ order.Item }}</td>
                <td width="800">{{ order.Qty }}</td>
                <td width="800">{{ order.Price }}</td>
                <td width="800">{{ order.Note }}</td>
                <td width="800">{{ order.OrderId }}</td>
                <td width="800">{{ order.Status }} 
                    <input type="text" name="food_status" placeholder="food_status" required=""/>
            </tr>
        </table>
    {% endfor %}
    <a href='' button onclick="myFunction()"><input type="submit" value="Change Status"></button>

</form>

代码应基于OrderId将food_status保存到food_status数据库列。

有人可以帮助我吗?真的很感激

1 个答案:

答案 0 :(得分:0)

更新的答案

您可以尝试这样

if request.method == "POST":
     status = OrderItem.objects.filter(
         OrderId__in=request.POST.get('OrderId', [])
     ).update(
         food_status=request.POST.get("food_status")
     )
return render(request, 'restaurants/kitchen_page.html', 
    {'chef_view':chef_view})