89π
The method all()
on a manager just delegates to get_queryset()
, as you can see in the Django source code:
def all(self):
return self.get_queryset()
So itβs just a way to get the QuerySet from the Manager. This can be handy to ensure that youβre dealing with a QuerySet and not a Manager, because MyModel.objects
returns a Manager.
For example, if you want to iterate over all the items, you canβt do this:
for item in MyModel.objects:
# this won't work
Because you canβt iterate over a Manager. However, all()
returns the QuerySet, you can iterate over a QuerySet:
for item in MyModel.objects.all():
# do someting with item
Generally, you should never overwrite all()
. You can overwrite get_queryset()
but this method must return a QuerySet.
If you would use a filter method like filter()
or exclude()
, you would already have the QuerySet, because these methods are proxied to the QuerySet. So you donβt have to do something like all().filter()
.
6π
MyModel.objects
returns the manager instance.all()
returnget_query_set()
. I think all is there for when you need all objects.- I prefer
MyModel.objects.filter()
cause the other is just one more method call, and I donβt need all objects if I do filter π - It depends on the purpose. But if they override a base method of the manager, they return the same result format (eg. a QuerySet)
- [Django]-In the Django admin interface, is there a way to duplicate an item?
- [Django]-Django set field value after a form is initialized
- [Django]-Model not showing up in django admin
-2π
Mymodel.objects.filter(username='abcd')
will give list of match record
Mymodel.objects.get(pk='abcd')
will return single record with matching on primary key value
- [Django]-How to use 'select_related' with get_object_or_404?
- [Django]-Django can' t load Module 'debug_toolbar': No module named 'debug_toolbar'
- [Django]-Embed YouTube video β Refused to display in a frame because it set 'X-Frame-Options' to 'SAMEORIGIN'