Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Django QuerySet: filter by the value of another field

I have a model I wish to filter by its attribute a. The model also has another attribute b. I am trying to filter entries where a is 0 or a has the value of the b attribute (for each row, obviously). How can I filter by the value of another column?

Here is what I have tried, and the missing piece:

MyModel.objects.filter(Q(a=0) | Q(a=???)) # ??? is to be the value of the `b` column

I am using Django 1.4 and I know it is an old version that is no longer supported but unfortunately performing the upgrade is not up to me.

like image 296
dabadaba Avatar asked Apr 19 '17 09:04

dabadaba


People also ask

Can I filter a QuerySet Django?

Working with Filter Easily the most important method when working with Django models and the underlying QuerySets is the filter() method, which allows you to generate a QuerySet of objects that match a particular set of filtered parameters.

What does QuerySet []> mean?

A QuerySet is a collection of data from a database. A QuerySet is built up as a list of objects. QuerySets makes it easier to get the data you actually need, by allowing you to filter and order the data.

How do I query in Django?

You get a QuerySet by using your model's Manager . Each model has at least one Manager , and it's called objects by default. Access it directly via the model class, like so: >>> Blog.objects <django.db.models.manager.Manager object at ...> >>> b = Blog(name='Foo', tagline='Bar') >>> b.objects Traceback: ...

What is PK in Django?

pk is short for primary key, which is a unique identifier for each record in a database. Every Django model has a field which serves as its primary key, and whatever other name it has, it can also be referred to as "pk".


2 Answers

I think you can use an F expression with your Q object:

MyModel.objects.filter(Q(a=0) | Q(a=F('b')))

I'll also suggest you schedule your upgrade now, otherwise, you'll be missing out on other features and security fixes.

like image 92
Moses Koledoye Avatar answered Oct 25 '22 21:10

Moses Koledoye


You can use the F model for comparing two fields.

from django.db.models import F
MyModel.objects.filter(a__exact = F('b'))

So for your joint query you can use something like,

MyModel.objects.filter(Q(a=0) | Q(a__exact=F('b')))
like image 35
Osiris92 Avatar answered Oct 25 '22 21:10

Osiris92