How to annotate Count with a condition in a Django queryset

For django >= 1.8 Use Conditional Aggregation: from django.db.models import Count, Case, When, IntegerField Article.objects.annotate( numviews=Count(Case( When(readership__what_time__lt=treshold, then=1), output_field=IntegerField(), )) ) Explanation: normal query through your articles will be annotated with numviews field. That field will be constructed as a CASE/WHEN expression, wrapped by Count, that will return 1 for readership matching criteria and NULL … Read more

Django filter JSONField list of dicts

If you wan’t to filter your data by one of fields in your array of dicts, you can try this query: Test.objects.filter(actions__contains=[{‘fixed_key_1’: ‘foo2’}]) It will list all Test objects that have at least one object in actions field that contains key fixed_key_1 of value foo2. Also it should work for nested lookup, even if you … 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

Django Order By Date, but have “None” at end?

Django 1.11 added this as a native feature. It’s a little convoluted. It is documented. Ordered with only one field, ascending: wo = Work_Order.objects.order_by(F(‘dateWORequired’).asc(nulls_last=True)) Ordered using two fields, both descending: wo = Work_Order.objects.order_by(F(‘dateWORequired’).desc(nulls_last=True), F(‘anotherfield’).desc(nulls_last=True))

django most efficient way to count same field values in a query

You want something similar to “count … group by”. You can do this with the aggregation features of django’s ORM: from django.db.models import Count fieldname=”myCharField” MyModel.objects.values(fieldname) .order_by(fieldname) .annotate(the_count=Count(fieldname)) Previous questions on this subject: How to query as GROUP BY in django? Django equivalent of COUNT with GROUP BY