Django基本管理

2024-09-28 01:26:32 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在使用project来了解Django Rest框架,但(对我来说)遇到了这个奇怪的代码

class AuthorManager(models.Manager):
    pass


class Author(models.Model):
    objects = AuthorManager()
    first_name = models.CharField(max_length=200)
    last_name = models.CharField(max_length=200)

    def __unicode__(self):
        return '{} {}'.format(self.first_name, self.last_name)

我不明白objects = AuthorManager()的目的,更进一步说,为什么我们使用一个只做pass的管理器。有什么原因吗


Tags: djangonameselfprojectrestobjectsmodelspass
1条回答
网友
1楼 · 发布于 2024-09-28 01:26:32

来自Django的文档:

A Manager is the interface through which database query operations are provided to Django models. At least one Manager exists for every model in a Django application.

这里,给定的模型管理器AuthorManager没有提供任何方法,因此没有任何意义。 将来,如果我们想使用任何方法,我们可以包括。比如,数一数作者的名字是“qarthandso”:

class AuthorManager(models.Manager):
    def count_qarthandso(self):
        super(AuthorManager, self).get_queryset().filter(first_name='qarthandso').count()

任何你可以使用的地方,比如:

Author.objects.count_qarthandso()

相关问题 更多 >

    热门问题