How to view corresponding SQL query of the Django ORM’s queryset?

Each QuerySet object has a query attribute that you can log or print to stdout for debugging purposes. qs = Model.objects.filter(name=”test”) print(qs.query) Note that in pdb, using p qs.query will not work as desired, but print(qs.query) will. If that doesn’t work, for old Django versions, try: print str(qs.query) Edit I’ve also used custom template tags … Read more

Optimizing database queries in Django REST framework

Django REST Framework cannot automatically optimize queries for you, in the same way that Django itself won’t. There are places you can look at for tips, including the Django documentation. It has been mentioned that Django REST Framework should automatically, though there are some challenges associated with that. This question is very specific to your … Read more

What’s the difference between select_related and prefetch_related in Django ORM?

Your understanding is mostly correct. You use select_related when the object that you’re going to be selecting is a single object, so OneToOneField or a ForeignKey. You use prefetch_related when you’re going to get a “set” of things, so ManyToManyFields as you stated or reverse ForeignKeys. Just to clarify what I mean by “reverse ForeignKeys” … Read more

Convert Django Model object to dict with all of the fields intact

There are many ways to convert an instance to a dictionary, with varying degrees of corner case handling and closeness to the desired result. 1. instance.__dict__ instance.__dict__ which returns {‘_foreign_key_cache’: <OtherModel: OtherModel object>, ‘_state’: <django.db.models.base.ModelState at 0x7ff0993f6908>, ‘auto_now_add’: datetime.datetime(2018, 12, 20, 21, 34, 29, 494827, tzinfo=<UTC>), ‘foreign_key_id’: 2, ‘id’: 1, ‘normal_value’: 1, ‘readonly_value’: 2} This … Read more

tech