如何创建一个 Django 查询集过滤器,比较同一模型中的两个日期字段

尝试获取在 Solr 索引中 Activity 记录过期的查询。 我想检查看看数据库中的 Activity.updated日期是否大于同一记录的 Activity.added_toSolr_date日期。

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

模特

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")

我引用了 Django Query 文档: Https://docs.djangoproject.com/en/1.4/ref/models/querysets/ 以及样本的单元测试: Https://github.com/django/django/blob/master/tests/modeltests/or_lookups/tests.py

也在 Stackoverflow 上搜索过。所有示例都使用输入的日期,而不是比较同一模型中的两个日期字段。

41637 次浏览

F objects.

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

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.