[英]Getting a query set between a range of dates Django
I'm trying to return a list of items in between 2 different dates, a date in the past and the current time using a queryset.我正在尝试使用查询集返回 2 个不同日期、过去日期和当前时间之间的项目列表。
The error I'm getting is TypeError: an integer is required (got type str)我得到的错误是TypeError: an integer is required (got type str)
views.py视图.py
import datetime
import pytz
first_date = "2020-01-01 19:17:35.909424"
last_date = timezone.now()
I don't want anything returned that has a date in the future我不希望返回任何有未来日期的东西
Here is the filter in the query这是查询中的过滤器
.filter(hide_sentance_until=(date(first_date), date(last_date)))
This is the full queryset, but it's the above filter causing he issue这是完整的查询集,但正是上述过滤器导致了他的问题
zip_flash_sentances = (
model.objects
.filter(show_sentance=True)
.filter(
hide_sentance_until=(date(first_date), date(last_date))
)
.order_by("?")
.filter(username_id = user_id_fk)
.values_list('sentance_eng', 'sentance_esp', 'id')
.first()
)
I thought it might be a comparison problem with dates but here is my model field我认为这可能是日期的比较问题,但这是我的模型字段
models.py模型.py
hide_sentance_until = models.DateTimeField(default=datetime.now(), blank=True)
Thanks谢谢
You can use gte
and lte
query attributes:您可以使用
gte
和lte
查询属性:
first_datetime = datetime.datetime.strptime(first_date, '%Y-%m-%d %H:%M:%S.%f')
last_date = timezone.now()
.filter(hide_sentance_until__lte=last_date,hide_sentance_until__gte=first_time)
One thing is that you're specifying a specific value that's determined when your code is compiled to be your default value.一件事是您指定了一个特定值,该值是在您的代码编译为默认值时确定的。 To have the actual current date be the value you want:
要使实际当前日期成为您想要的值:
hide_sentance_until = models.DateTimeField(default=datetime.now, blank=True)
Then you need to parse the datetime out of the string.然后你需要从字符串中解析出日期时间。
date_value = datetime.strptime(first_date, DATETIME_FORMAT_YOU_USE)
Where DATETIME_FORMAT_YOU_USE is the series of format codes from Python that you're using.其中 DATETIME_FORMAT_YOU_USE 是您正在使用的Python 格式代码系列。
Finally you should use the __range
queryset field lookup.最后,您应该使用
__range
查询__range
字段查找。
.filter(
hide_sentance_until__range=(date_value, timezone.now())
)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.