Django模型已保存,但返回None [英] Django Model is saved, but returns None

查看:427
本文介绍了Django模型已保存,但返回None的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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

当我现在尝试将对象保存在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>

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

推荐答案

因为超类save方法不返回任何内容.不需要:保存self,返回其他内容并将其命名为obj是没有意义的.

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.

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

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.

这篇关于Django模型已保存,但返回None的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆