Django Model已保存,但返回None


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

    def get_rating_for_field(self, installer, field):
            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 =
In [4]: obj
In [5]: company_obj
Out[5]: <CompanyReview: AdminCompany>

Why is the 3rd step failing without an error?


3 years ago

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

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