我想在.save()之前和之后比较一个字段(manytomany)来知道该条目已被删除。我试过了:
def save(self):
differentiate_before_subscribed = Course.objects.get(id=self.id).subscribed.all()
super(Course, self).save() # Call the "real" save() method.
differentiate_after_subscribed = Course.objects.get(id=self.id).subscribed.all()
#Something
但是differentiate_before_subscribed和differentiate_after_subscribed都有相同的值。我必须使用信号吗?怎么样?
修改:
def addstudents(request, Course_id):
editedcourse = Course.objects.get(id=Course_id) # (The ID is in URL)
# Use the model AssSubscribedForm
form = AddSubscribedForm(instance=editedcourse)
# Test if its a POST request
if request.method == 'POST':
# Assign to form all fields of the POST request
form = AddSubscribedForm(request.POST, instance=editedcourse)
if form.is_valid():
# Save the course
request = form.save()
return redirect('Penelope.views.detailcourse', Course_id=Course_id)
# Call the .html with informations to insert
return render(request, 'addstudents.html', locals())
# The course model.
class Course(models.Model):
subscribed = models.ManyToManyField(User, related_name='course_list', blank=True, null=True, limit_choices_to={'userprofile__status': 'student'})
答案 0 :(得分:2)
当您save a model form时,首先保存实例,然后单独调用方法save_m2m
(除非您使用save_m2m
保存表单,否则会自动调用commit=False
在哪种情况下你必须手动调用它)。对于两个查询集,您都会得到相同的结果,因为稍后会保存多对多字段。
您可以尝试使用m2m_changed
信号来跟踪多对多字段的更改。
Django querysets are lazy。在这种情况下,直到模型保存后才会计算第一个查询集,因此它返回与第二个查询集相同的结果。
您可以使用list
强制对查询集进行评估。
differentiate_before_subscribed = list(Course.objects.get(id=self.id).subscribed.all())