5

I have a simple model with a Model Manager:

class CompanyReviewManager(models.Manager):
    def get_votes_for_company(self, company):
        try:
            return CompanyReview.objects.filter(user = user).count()
        except ObjectDoesNotExist:
            return None

    def get_rating_for_field(self, installer, field):
        try:
            return CompanyReview.objects.filter(user = user).aggregate(Avg(field))
        except ObjectDoesNotExist:
            return None

class CompanyReview(models.Model):
    user = models.ForeignKey(settings.AUTH_USER_MODEL)
    satisfaction = models.PositiveSmallIntegerField(blank = True, null = True,)
    comments = models.TextField(blank = True, null = True,)

    objects = CompanyReviewManager()

    def save(self, *args, **kwargs):
        obj = super(InstallerReview, self).save(*args, **kwargs)
        return obj

When I now try to save an object in the Django shell, the object will be saved, but nothing will be returned. Why?

In [1]: company_obj = InstallerReview()
In [2]: company_obj.user = CompanyUser.objects.all()[2]
In [3]: obj = company_obj.save()
In [4]: obj
Out[4]: 
In [5]: company_obj
Out[5]: <CompanyReview: AdminCompany>

Why is the 3rd step failing without an error?

Urda
  • 5,460
  • 5
  • 34
  • 47
neurix
  • 4,126
  • 6
  • 46
  • 71
  • @Urda I might be missing something here, but I don't see how this is especially 1.5 related. And why adding "Django" back in the title ? It is tagged as a Django question already. – Anto Jul 18 '14 at 01:16

1 Answers1

23

Because the super class save method doesn't return anything. It doesn't need to: self is being saved, there's no point returning something else and calling it obj.

You could just return self from your subclass save method, but there's not much point. Generally in Python, if functions change objects in-place, they do not return the changed object: compare with the list sort() method.

Daniel Roseman
  • 588,541
  • 66
  • 880
  • 895