How to create a Django queryset filter comparing two date fields in the same model

Carlos Ferreira picture Carlos Ferreira · Sep 12, 2012 · Viewed 31.3k times · Source

Trying to get a query where the Activity record is stale in my Solr Index. I want to check to see if the Activity.updated date in the database is greater than the Activity.added_toSolr_date for the same record.

stale_activities_queryset = Activity.objects.filter(updated__gte = self.added_toSolr_date) 

Model

class Activity(models.Model):
    # Last time entry / metric was updated in the Activity model database
    updated =  models.DateTimeField( verbose_name="CRUD date")
    # When it was added to Solr Index Date
    added_toSolr_date = models.DateTimeField(blank=True, null=True, verbose_name="Added to Solr Index Date")

I referenced Django Query docs: https://docs.djangoproject.com/en/1.4/ref/models/querysets/ And unit tests for samples: https://github.com/django/django/blob/master/tests/modeltests/or_lookups/tests.py

Also searched here on Stackoverflow. All the examples use an entered date instead of comparing two date fields in the same model.

Answer

Yuji 'Tomita' Tomita picture Yuji 'Tomita' Tomita · Sep 12, 2012

F objects.

from django.db.models import F
stale_activities = Activity.objects.filter(updated__gte=F('added_toSolr_date'))