Recently, I saw a code like this in a 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, )
There are several usages of which the function is unknown:
First, we get a Model class whose _default_manager is What? Judging from the following methods, it should be an instance of manager, but this Manager refers to What? If I customize a manager in the model, for example
objects = MyManager()Is this _default_Manager pointing to this custom manager or django’s default manager ()?
_state.db refers to What? The _state of a model instance is What? . db is What? again What is the effect?
Why do you want to write this, what’s the advantage? Can’t you just write self.get _ comment _ model (). objects.filter ()?
I looked at the source code related to the model. It’s foggy in inside. Please give me some advice!
_default_manager represents the default manager of 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/.
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.