I have seen that queries like :
user = User.objects.all() or User.objects.filter(username = username)
will fetch all the columns of the table even if we do not need all the columns. Do we have a better way of writing a database query? and if yes why do we not see that code most often?
The __lte lookup [Django-doc] means that you constrain the field that is should be less than or equal to the given value, whereas the __gte lookup [Django-doc] means that the field is greater than or equal to the given value. So for example: MyModel.objects.
If you want to get distinct objects, instead of values, then remove flat=True from the above query, and use values() instead of values_list(). In the above code, we add distinct() at the end of queryset to get distinct values.
QuerySet.only()
and QuerySet.defer()
can be used to refine which fields the ORM will pull, deferring the others until the appropriate attributes on the models are accessed.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With