Django模型已保存,但返回None

时间:2013-05-10 15:25:17

标签: django django-models django-1.5

我有一个模型管理器的简单模型:

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

当我现在尝试在Django shell中保存一个对象时,该对象将被保存,但不会返回任何内容。为什么?

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>

为什么第3步失败没有错误?

1 个答案:

答案 0 :(得分:20)

因为超类save方法没有返回任何内容。它不需要:self正在保存,没有必要返回其他内容并将其称为obj

您可以从子类self方法返回save,但没有多大意义。通常在Python中,如果函数就地更改对象,则它们不会返回更改的对象:与列表sort()方法进行比较。