Compare field before and after saving ()

I want to compare the (manytomany) field before and after .save () to find out which record was deleted. I 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 

But both differiate_before_subscribed and differiate_after_subscribed have the same meaning. Should I use signals? And How?

Edit:

 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'}) 
+2
source share
1 answer

When you save the model form , the instance is saved first, then the save_m2m method is called separately ( save_m2m is called automatically if you do not save the form using commit=False , in which case you must call it manually). You get the same result for both sets of queries, because much is saved for many fields later.

You can try using the m2m_changed signal to track changes in the many to many field.

Original sentence (does not work):

Django requests are lazy . In this case, the first query is not evaluated until the model is saved, so it returns the same results as the second query.

You can force a query using list .

 differentiate_before_subscribed = list(Course.objects.get(id=self.id).subscribed.all()) 
+2
source

Source: https://habr.com/ru/post/921478/


All Articles