Django ORM - objects.filter() vs. objects.all().filter() - which one is preferred?

前端 未结 3 1014
不知归路
不知归路 2020-12-28 11:49

Very often I see constructs like

MyModel.objects.all().filter(...)

which will return a QuerySet of the default Mananger. At first al

相关标签:
3条回答
  • 2020-12-28 12:30

    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:
        # do something with item
    

    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 something 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().

    0 讨论(0)
  • 2020-12-28 12:37

    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

    0 讨论(0)
  • 2020-12-28 12:47
    1. MyModel.objects returns the manager instance. all() return get_query_set(). I think all is there for when you need all objects.
    2. 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 :)
    3. It depends on the purpose. But if they override a base method of the manager, they return the same result format (eg. a QuerySet)
    0 讨论(0)
提交回复
热议问题