python - Django 的 _default_manager 指的是什么?
高洛峰
高洛峰 2017-04-17 17:56:07
0
3
570

最近在某个 Django 的 app 中看到这样的一段代码:

possible_duplicates = self.get_comment_model()._default_manager.using(
            self.target_object._state.db
        ).filter(
            content_type=new.content_type,
            object_pk=new.object_pk,
            user_name=new.user_name,
            user_email=new.user_email,
            user_url=new.user_url,
        )

其中有几个用法不知道其作用:

  1. 首先我们得到了一个 Model 类,其 _default_manager 是什么?从其后面的方法来看应该是一个 Manager 的实例,但是这个 manager 指的是什么?如果我在 model 中自定义了一个 manager,比如 objects = MyManager(),那么这个 _default_manager 指向的是这个自定义的 manager 还是 django 默认的 Manager()?

  2. _state.db 指的是什么?一个 model 实例的 _state 是什么? .db 又是什么?有什么作用?

  3. 为什么要这么写,有什么好处?不能直接写成 self.get_comment_model().objects.filter()么?

看了看 model 相关的源码,云里雾里的,求大家指点!

高洛峰
高洛峰

拥有18年软件开发和IT教学经验。曾任多家上市公司技术总监、架构师、项目经理、高级软件工程师等职务。 网络人气名人讲师,...

reply all(3)
巴扎黑

_default_manager represents the default manager of the Model. If you define your own manager, the first manager will be considered the default manager.
You can refer to Django’s documentation https://docs.djangoproject.com/en/1.9/topics/db/managers/.

Default managers¶

If you use custom Manager objects, take note that the first Manager
Django encounters (in the order in which they're defined in the model)
has a special status. Django interprets the first Manager defined in a
class as the “ default” Manager, and several parts of Django (including
dumpdata) will use that Manager exclusively for that model. As a
result, it's a good idea to be careful in your choice of default
manager in order to avoid a situation where overriding get_queryset()
results in an inability to retrieve objects you'd like to work with.

伊谢尔伦

You should post these two pieces of code, self.get_comment_model() and self.target_object together, otherwise others may not be able to answer the answer you want by guessing

刘奇

Thank you, part of the solution is solved, .using(

        self.target_object._state.db
    ).filter
The part of

indicates using the table of the database where the target_object (Model instance) is located to query, mainly to meet cross-site needs.

Also, _default_manager represents something that has not been resolved yet.

Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template