Django日期和月份事件日期查询 [英] Django day and month event date query

查看:129
本文介绍了Django日期和月份事件日期查询的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个django模型,如下所示:

  class Event(models.Model):
name = model.CharField(... etc ...)
date = model.DateField(... etc ...)

我需要的是获取所有在特定日期和月份的活动的方法 - 非常像在这一天页面。


$ b $
$ b $ / code code code $ f code $ pre>

我已经尝试了所有的常规日期查询类型,但是它们似乎都需要一年,而不是遍历所有年我无法看到如何做到这一点。

解决方案

您可以通过指定日期和月:

  def on_this_day(日,月):
返回Event.objects.filter(date__day = day,date__month =月)

最有可能扫描您的数据库表,使用SQL运算符个月(日期) DAY(日期)或某些查找等价物



您可能会收到更好的查询性能,如果您添加和索引 Event.day Event.month (如果事件.date 在数据库中内部存储为 int ,它使其不太适合您的(日,月) 查询)



以下是Django的一些文档: https://docs.djangoproject.com/en/dev/ref/models/querysets/#month


I have a django model that looks like this:

class Event(models.Model):
    name = model.CharField(...etc...)
    date = model.DateField(...etc...)

What I need is a way to get all events that are on a given day and month - much like an "on this day" page.

def on_this_day(self,day,month):
    reutrn Events.filter(????)

I've tried all the regular date query types, but they all seem to require a year, and short of iterating through all years, I can't see how this could be done.

解决方案

You can make a query like this by specifying the day and the month:

def on_this_day(day, month):
    return Event.objects.filter(date__day=day, date__month=month)

It most likely scans your database table using SQL operators like MONTH(date) and DAY(date) or some lookup equivalent

You might get a better query performance if you add and index Event.day and Event.month (if Event.date is internally stored as an int in the DB, it makes it less adapted to your (day, month) queries)

Here's some docs from Django: https://docs.djangoproject.com/en/dev/ref/models/querysets/#month

这篇关于Django日期和月份事件日期查询的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆