Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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.

like image 541
Carlos Ferreira Avatar asked Sep 12 '12 02:09

Carlos Ferreira


People also ask

Can I filter a QuerySet Django?

The filter() method is used to filter you search, and allows you to return only the rows that matches the search term.

What is the difference between filter and get method in Django?

Basically use get() when you want to get a single unique object, and filter() when you want to get all objects that match your lookup parameters.

How do I combine QuerySet?

Use union operator for queryset | to take union of two queryset. If both queryset belongs to same model / single model than it is possible to combine querysets by using union operator. One other way to achieve combine operation between two queryset is to use itertools chain function. Instead of itertools.

How filter unique values Django?

If you want to get distinct objects, instead of values, then remove flat=True from the above query, and use values() instead of values_list(). In the above code, we add distinct() at the end of queryset to get distinct values.


1 Answers

F objects.

from django.db.models import F stale_activities = Activity.objects.filter(updated__gte=F('added_toSolr_date'))  
like image 172
Yuji 'Tomita' Tomita Avatar answered Sep 27 '22 20:09

Yuji 'Tomita' Tomita