最近在某个 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,
)
其中有几个用法不知道其作用:
首先我们得到了一个 Model 类,其 _default_manager 是什么?从其后面的方法来看应该是一个 Manager 的实例,但是这个 manager 指的是什么?如果我在 model 中自定义了一个 manager,比如 objects = MyManager()
,那么这个 _default_manager 指向的是这个自定义的 manager 还是 django 默认的 Manager()?
_state.db 指的是什么?一个 model 实例的 _state 是什么? .db 又是什么?有什么作用?
为什么要这么写,有什么好处?不能直接写成 self.get_comment_model().objects.filter()么?
看了看 model 相关的源码,云里雾里的,求大家指点!
_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/.
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(
The part ofindicates 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.