In a Django QuerySet, how to filter for “not exists” in a many-to-one relationship

Note: this answer was written in 2013 for Django 1.5. See the other answers for better approaches that work with newer versions of Django Use isnull. users_without_reports = User.objects.filter(report__isnull=True) users_with_reports = User.objects.filter(report__isnull=False).distinct() When you use isnull=False, the distinct() is required to prevent duplicate results.

Why does django’s prefetch_related() only work with all() and not filter()?

In Django 1.6 and earlier, it is not possible to avoid the extra queries. The prefetch_related call effectively caches the results of a.photoset.all() for every album in the queryset. However, a.photoset.filter(format=1) is a different queryset, so you will generate an extra query for every album. This is explained in the prefetch_related docs. The filter(format=1) is … Read more

How to update() a single model instance retrieved by get() on Django ORM?

With the advent of Django 1.7, there is now a new update_or_create QuerySet method, which should do exactly what you want. Just be careful of potential race conditions if uniqueness is not enforced at the database level. Example from the documentation: obj, created = Person.objects.update_or_create( first_name=”John”, last_name=”Lennon”, defaults={‘first_name’: ‘Bob’}, ) The update_or_create method tries to … Read more

Select DISTINCT individual columns in django?

One way to get the list of distinct column names from the database is to use distinct() in conjunction with values(). In your case you can do the following to get the names of distinct categories: q = ProductOrder.objects.values(‘Category’).distinct() print q.query # See for yourself. # The query would look something like # SELECT DISTINCT … Read more

Django select only rows with duplicate field values

Try: from django.db.models import Count Literal.objects.values(‘name’) .annotate(Count(‘id’)) .order_by() .filter(id__count__gt=1) This is as close as you can get with Django. The problem is that this will return a ValuesQuerySet with only name and count. However, you can then use this to construct a regular QuerySet by feeding it back into another query: dupes = Literal.objects.values(‘name’) .annotate(Count(‘id’)) … Read more

Why is iterating through a large Django QuerySet consuming massive amounts of memory?

Nate C was close, but not quite. From the docs: You can evaluate a QuerySet in the following ways: Iteration. A QuerySet is iterable, and it executes its database query the first time you iterate over it. For example, this will print the headline of all entries in the database: for e in Entry.objects.all(): print … Read more

Select distinct values from a table field

Say your model is ‘Shop’ class Shop(models.Model): street = models.CharField(max_length=150) city = models.CharField(max_length=150) # some of your models may have explicit ordering class Meta: ordering = (‘city’,) Since you may have the Meta class ordering attribute set (which is tuple or a list), you can use order_by() without parameters to clear any ordering when using … Read more