我有一个页面可以编辑模型中的现有数据。
模型:
class billitem(models.Model):
code = models.AutoField(primary_key=True, unique=True)
name = models.CharField(max_length=35)
description = models.CharField(max_length=60, null=True)
price = models.DecimalField(decimal_places=2, max_digits=8)
表格:
class BillItem(forms.Form):
code = forms.IntegerField(max_value=100000, disabled=True)
name = forms.CharField(label='Item Name', max_length=32)
description = forms.CharField(
label='Description', max_length=57, required=False)
price = forms.DecimalField(decimal_places=2, max_digits=8)
视图是:
def edit_bill_item(request, itemcode):
if request.method == 'POST':
form = BillItem(request.POST)
code = request.POST.get('code')
name = request.POST.get('name').title()
description = request.POST.get('description')
price = request.POST.get('price')
billitem.objects.filter(code=code).update(
name=name, description=description, price=price)
msg = 'Successfully saved Billing item.'
# form = BillItem(request.POST)
return render(request, 'billing/edititem.html', {'form': form, 'msg': msg})
else:
itemcode = int(itemcode)
item = get_object_or_404(billitem, code=itemcode)
form = BillItem(initial={
'code': item.code,
'name': item.name,
'description': item.description,
'price': item.price
})
return render(request, 'billing/edititem.html', {'form': form})
问题在于,每次提交POST时,表中都会使用新代码添加另一个条目,而不是更新现有行。
我也尝试过:
item = billitem(code=code, name=name, description=description, price=price)
item.save()
备用:
class BillItem(ModelForm):
class Meta:
model = billitem
fields = ['code', 'name', 'description', 'price']
def edit_bill_item(request, itemcode):
if request.method == 'POST':
code = request.POST.get('code')
name = request.POST.get('name').title()
description = request.POST.get('description')
price = request.POST.get('price')
item = billitem.objects.get(code=code)
form = BillItem(request.POST, instance=item)
form.save()
msg = 'Successfully saved Billing item.'
return render(request, 'billing/edititem.html', {'form': form, 'msg': msg})
else:
itemcode = int(itemcode)
item = get_object_or_404(billitem, code=itemcode)
form = BillItem(initial={
'code': item.code,
'name': item.name,
'description': item.description,
'price': item.price
})
return render(request, 'billing/edititem.html', {'form': form})
也有同样的效果。 如何仅在模型和表单中处理现有数据的更新。
答案 0 :(得分:0)
更改此行:
billitem.objects.filter(code=code).update(name=name, description=description, price=price)
要使用内置的update_or_create函数(https://docs.djangoproject.com/en/dev/ref/models/querysets/#update-or-create)
BillItem.objects.update_or_create(code=code, defaults={'name':'name', 'description':'description', 'price':'price})