【问题标题】:How to filter Django queryset by non field values如何按非字段值过滤 Django 查询集
【发布时间】:2018-10-28 11:44:02
【问题描述】:

我需要按当地时间查询模型。

send_reminder_query = PersonModel.objects.filter('Is after 7pm thier localtime')

此人将有一个邮政编码字段,我有一个通过他们的邮政编码获取时区的功能。我也愿意编写一个迁移脚本来填充 Person 模型上的时区,但我仍然不知道如何进行查询。

send_reminder_query = PersonModel.objects.filter(tzinfo='...', ?)

【问题讨论】:

  • 显示您的PersonModel 模型。
  • 你怎么知道他们的“当地时间”?您是否存储了有关它们的更多信息?
  • 我只知道他们的邮政编码,但从中我可以知道他们的时区。

标签: django python-3.x django-models django-queryset


【解决方案1】:

我能够通过预处理数据来存储人的时区来解决这个问题。然后使用pytz 我这样做。

from django.utils import timezone 
import pytz


valid_timezones = []
for tz in list_of_timezones:
    local_time =  now().astimezone(pytz.timezone(tz))
    if 19 < local_time.hour < 20:
        valid_timezones.append(tz)

reminders = Person.objects.filter(timezone__in=valid_timezones)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2015-05-06
    • 1970-01-01
    • 2015-04-03
    • 2014-06-14
    • 1970-01-01
    • 2016-02-01
    相关资源
    最近更新 更多