Category index for “sql”
Trap in counting related objects in Django
Task: for every object count number of related objects satisfying some conditions.
Trying JSON in Django and PostgreSQL (and compare with MongoDB)
New JSONField will be added in Django 1.9, it can be used with PostgreSQL >= 9.4. Let’s try to work with it and find out, in what situations it can be useful.
Debug SQL in django test
In django tests we can measure number of sql queries:
def test_home(self): with self.assertNumQueries(1): response = self.client.get('/') self.assertEqual(response.status_code, 200)
If code in context of
assertNumQueries
will make other number of DB attempts than expected (here 1), test will throw error. But when test fails it is sometimes hard to understand, what unexpected query was made. To debug such case very useful to log SQL expressions to console. Below is description how to do it.Nested SQL queries in Django
Did you know, that Django ORM can do nested SQL queries? Shame on me, but i’ve found it not so long ago.
Django queryset.count cache
Once I mentioned, that my django application makes several similiar queries like
SELECT COUNT(*) ...
. As it turns out (for me it was surprise),queryset.count()
has not obvious cache. But let me start the story from the beginning (and sorry for my english :) ).Django admin site optimisation
It is known, that less amount of database attempts leads to better performance. Usually admin page - part of site with low traffic, but anyway it is good, if no additional database calls happen there. It is more pleasant to use it, because page renders faster and also frees server resources.
In this post i’ll try to reduce some database attempts in admin page, when model method
__unicode__
contains related object field. I suppose, that examples describe the situation more clear.