Django update queryset with annotation

For Django 1.11+ you can use Subquery: from django.db.models import OuterRef, Subquery, Sum Relation.objects.update( rating=Subquery( Relation.objects.filter( id=OuterRef(‘id’) ).annotate( total_rating=Sum(‘sign_relations__rating’) ).values(‘total_rating’)[:1] ) ) This code produce the same SQL code proposed by Tomasz Jakub Rup but with no use of RawSQL expression. The Django documentation warns against the use of RawSQL due to the possibility of … Read more

django select_related – when to use it

You are actually asking two different questions: 1. does using select_related actually creates performance overhead? You should see documentation about Django Query Cache: Understand QuerySet evaluation To avoid performance problems, it is important to understand: that QuerySets are lazy. when they are evaluated. how the data is held in memory. So in summary, Django caches … Read more

Django Count() in multiple annotations

I think Count(‘topics’, distinct=True) should do the right thing. That will use COUNT(DISTINCT topic.id) instead of COUNT(topic.id) to avoid duplicates. User.objects.filter( username_startswith=”ab”).annotate( posts=Count(‘post’, distinct=True)).annotate( topics=Count(‘topic’, distinct=True)).values_list( “username”,”posts”, “topics”)

prefetch_related for multiple Levels

Since Django 1.7, instances of django.db.models.Prefetch class can be used as an argument of .prefetch_related. Prefetch object constructor has a queryset argument that allows to specify nested multiple levels prefetches like that: Project.objects.filter( is_main_section=True ).select_related( ‘project_group’ ).prefetch_related( Prefetch( ‘project_group__project_set’, queryset=Project.objects.prefetch_related( Prefetch( ‘projectmember_set’, to_attr=”projectmember_list” ) ), to_attr=”project_list” ) ) It is stored into attributes with _list … Read more

Django query case-insensitive list match

Unfortunatley, there are no __iin field lookup. But there is a iregex that might be useful, like so: result = Name.objects.filter(name__iregex=r'(name1|name2|name3)’) or even: a = [‘name1’, ‘name2’, ‘name3’] result = Name.objects.filter(name__iregex=r'(‘ + ‘|’.join(a) + ‘)’) Note that if a can contain characters that are special in a regex, you need to escape them properly. NEWS: … Read more