David542
David542

Reputation: 110093

Comparing two fields in django queryset

How would I do the following SQL query in the Django ORM?

SELECT * FROM my_table WHERE date_added > date_created;

Upvotes: 5

Views: 3818

Answers (3)

Wolph
Wolph

Reputation: 80011

I'm guessing you don't have the date_created available as a variable (as @tttthomasssss assumes) so it will be something like this:

from django.db import models

YourTable.objects.filter(date_added__gt=models.F('date_created')

Docs on F expressions: https://docs.djangoproject.com/en/dev/ref/models/expressions/#f-expressions

Upvotes: 8

tttthomasssss
tttthomasssss

Reputation: 5971

You can use __gt for >: MyModel.objects.filter(date_added__gt=date_created).

See the documentation for querysets here.

EDIT: If date_created isn't available to you, then @Wolph's solution is the one.

Upvotes: 1

Norman8054
Norman8054

Reputation: 824

You can use F() expressions in queries like this:

MyModel.objects.filter(date_added__gt=F('date_created'))

Upvotes: 1

Related Questions