nlassaux
nlassaux

Reputation: 2406

Compare field before and after save()

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'})

Upvotes: 2

Views: 1145

Answers (1)

Alasdair
Alasdair

Reputation: 308909

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())

Upvotes: 2

Related Questions