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

喜你入骨 提交于 2019-12-28 05:07:21

问题


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.


回答1:


F objects.

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



回答2:


The solution of Yuji Tomita, unfortunately, didn't work.

Consider a model below:

class list(models.Model):
    text = models.CharField(max_length=140)
    created = models.DateTimeField()
    modified = models.DateTimeField()

Queryset:

my_list = todolist.objects.order_by('created').filter(created__gte=F('modified'))

Template:

{% if my_list %}
{% for list in my_list %}
{{ list.text}}
{% endfor %}
{% else %}
<p>there is no list</p>
{% endif %}

In the end I get an empty list, but I know, it is not correct. I have also used the following inside the template (without queryset filter):

{% if list.created|date:'d m y h:i:s' == list.modified|date:'d m y h:i:s' %}

It worked, but I would prefer to see a more elegant solution.



来源:https://stackoverflow.com/questions/12380448/how-to-create-a-django-queryset-filter-comparing-two-date-fields-in-the-same-mod

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!