Django Query using value from another field in same table

I came across a query that seemed like it should be pretty easy, but it wasn’t.

Suppose you have the following Model Class.

# pseudo code.
class Person(models.Model):
first_name = models.CharField()
last_name = models.CharField()
I would like the query to return all Person’s who have the same first_name and last_name

My first guess was to do the following.

person_list = Person.objects.filter(first_name=last_name)

but that doesn’t work because it wants to have last_name as a variable.

This is what I ended up doing.

person_list = Person.objects.extra(where=[‘first_name=last_name’]

You could also do it using a models.Manager, if that is what you prefer.

Even though this is an edge case, I’m not sure why Django doesn’t support this out of the box, but I am pretty sure there is a pretty good reason.

Share