我刚开始学习django并且我遇到了一个问题。我不知道如何更新数据库行(字段)。当我打电话给form_valid时,我的数据库表正在添加额外的信息。
是的,我读到了这个:How to update an object from edit form in Django?
但它对我不起作用。它每次都会添加更多信息。
View.py
def form_valid(self, form, **kwargs):
print 'heeee'
students = Student.objects.all()
studies = Student_in_Subgroup.objects.all()
subgroups = Subgroup.objects.all()
lists = self.request.POST.getlist('studs[]')
sum = 0
for student in students:
for l in lists:
if student.id == int(l):
for studie in studies:
if studie.student_Id.id == student.id:
for subgroup in subgroups:
if studie.subgroup_Id.id == subgroup.id:
print student.id
studentId = student.id
key = subgroup.student_group_id
sum = sum + 1
if subgroup.number == None:
continue
subgroupId = studie.subgroup_Id.id
if (self.request.POST.get('act1')=='add'):
#problem sowhere here I THINK
instance = get_object_or_404(Subgroup, id=subgroupId)
form = ApplicationFormaFull1(self.request.POST or None, instance=instance)
form.save()
#problem sowhere here I THINK
xxx=form['sub']
xxx.student_group = StudentGroup.objects.get(id=key)
xxx.number = self.request.POST.get('act2')
xxx.type = self.request.POST.get('act3')
xxx.stundent_count = sum
xxx.save()
yyy=form['stud_sub']
yyy.subgroup_Id = Subgroup.objects.get(id=subgroupId)
yyy.student_Id = Student.objects.get(id=studentId)
yyy.save()
else:
print('no')
return super(IndexView, self).form_valid(form)
Form.py
class FormSubgroup(forms.ModelForm):
class Meta:
model = Subgroup
exclude = ['student_group','number','type','student_count']
class FormStudent_in_Subgroup(forms.ModelForm):
class Meta:
model = Student_in_Subgroup
exclude = ['subgroup_Id','student_Id']
class ApplicationFormaFull1(MultiModelForm):
form_classes = {
'sub': FormSubgroup,
'stud_sub': FormStudent_in_Subgroup
}
也许有人知道解决方案
答案 0 :(得分:-1)
要编辑模型中的信息,请使用.update。例如,Student.objects.filter(id = studentId).update(fieldname = newvalue)