2

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

But both differentiate_before_subscribed and differentiate_after_subscribed have same value. I have to 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'})
Jason Aller
  • 3,541
  • 28
  • 38
  • 38
nlassaux
  • 2,335
  • 2
  • 21
  • 35

1 Answers1

2

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.

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

Initial suggestion (didn't work):

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.

You can force the queryset to be evaluated by using list.

differentiate_before_subscribed = list(Course.objects.get(id=self.id).subscribed.all())
Alasdair
  • 298,606
  • 55
  • 578
  • 516
  • It doesn't works : the value of both is the value before the .save(), so this is the `differentiate_after_subscribed`that is not updated. I have tested the list() methode on `differentiate_after_subscribed`and it doesn't change... – nlassaux Jul 26 '12 at 22:47
  • Is this the model or form `save` method you are overriding? Can you update your question with your model, and the view you are calling `save()` from? – Alasdair Jul 26 '12 at 23:06