Django Model已保存,但返回None

loading...


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

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?

1回答

  • 20

    因为超类 save 方法不需要: self 正在保存,所以没有必要返回其他内容并将其命名为 obj .

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

loading...

评论

暂时没有评论!