在save()之前和之后比较字段 [英] Compare field before and after save()
问题描述
我想比较.save()之前和之后的字段(manytomany),以了解哪些条目已被删除.我已经尝试过:
I want to compare a field (manytomany) before and after a .save() to know which entries have been deleted. I have tried:
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
但是different_before_subscribed和different_after_subscribed具有相同的值.我必须使用信号吗?以及如何?
But both differentiate_before_subscribed and differentiate_after_subscribed have same value. I have to use signals? And how?
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'})
推荐答案
When you save a model form, first the instance is saved, then the method save_m2m
is called separately (save_m2m
is called automatically unless you save the form with commit=False
, in which case you must call it manually). You get the same result for both query sets because the many to many field is saved later.
您可以尝试使用 m2m_changed
信号以跟踪多对多字段的变化.
You could try using the m2m_changed
signal to track changes to the many to many field.
Django 查询集是懒惰的.在这种情况下,只有在保存模型之后才评估第一个查询集,因此它返回的结果与第二个查询集相同.
Django querysets are lazy. In this case, the first queryset is not evaluated until after the model has been saved, so it returns the same results as the second queryset.
您可以使用 list
强制对查询集进行评估.
You can force the queryset to be evaluated by using list
.
differentiate_before_subscribed = list(Course.objects.get(id=self.id).subscribed.all())
这篇关于在save()之前和之后比较字段的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!