我正在尝试向医生对象添加喜欢和不喜欢的计数,但它似乎没有对医生模型进行任何更改。该视图用于成功将数据保存在另一个模型中的表单。但医生模型没有任何改变。整个视图工作正常,除了医生喜欢的线条,不喜欢和netlikes似乎没有任何变化。所有这三个都是医生模型中的字段。
def addContent(request, id):
d = getVariables(request)
doctor = Doctor.objects.get(id=id)
if request.user.is_authenticated():
user = request.user
ds = DoctorSeeker.objects.get(user=user)
d['doctorseeker'] = ds
if request.method == "POST":
form = UserContentForm(request.POST)
if form.is_valid():
time = form.cleaned_data['time']
comment = form.cleaned_data['comment']
if request.POST.get('Like') == 'Like':
con = UserContent(time=time, comment = comment, liked = True, disliked = False, doctor_id = doctor.id, user_id = request.user.id)
doctor.likes += 1
doctor.netlikes = doctor.likes - doctor.dislikes
con.save()
elif request.POST.get('Like') == 'Dislike':
con = UserContent(time=time, comment = comment, liked = False, disliked = True, doctor_id = doctor.id, user_id = request.user.id)
doctor.dislikes +=1
doctor.netlikes = doctor.likes - doctor.dislikes
con.save()
url = '/docprofile/%s' % str(doctor.id)
return HttpResponseRedirect(url)
else:
form = UserContentForm()
d.update({'doctor': doctor, 'UGC': UserContent.objects.all(),
'form': form })
return render(request, 'meddy1/usercontent.html',d)
答案 0 :(得分:1)
您不会将医生实例保存在任何地方。
doctor.dislikes += 1
doctor.save()
(你也可以考虑一下你是否真的需要在一个字段中存储'netlikes':最好将它作为模型上的一个简单方法,只返回self.likes - self.dislikes
。)
答案 1 :(得分:0)
我建议您使用F()表达式来处理喜欢和不喜欢的事情。它将在数据库级别递增它们,而不是从内存中获取过时的值。以下是F() expressions
上官方文档的链接所以代码看起来像这样
doctor.dislikes = F('dislikes') + 1
doctor.save()