如何在 Django 模型上定义任何年份的月份范围?
我有一个名为 Event 的 Django 模型,它有一个事件日期的日期字段:
class Event(models.Model):
event_date = models.DateField()
我希望能够在模型上设置一个方法来判断该事件是“春季学期”活动还是“秋季学期”活动“ 事件。
春季学期定义为一月至五月。秋季是八月到十二月。
我的目标是能够在一年的通用事件列表中按任一学期进行过滤。
我将如何编写定义每个学期的方法?
I have a Django model called Event that has a date field for the date of the event:
class Event(models.Model):
event_date = models.DateField()
I'd like to be able to set a method on the model to tell whether the event is a "spring semester" event or a "fall semester" event.
The spring semester would be defined as January to May. Fall is August to December.
My goal is to be able to filter by either semester in a generic list of events for a year.
How would I go about writing the method defining each semester?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
一种方法是:
然后在一个视图中你可以这样做:
希望对你有帮助。
One approach is:
Then in a view you can do:
Hope that helps you out.
你看过 django 的 Models 方法吗?你可以在这里找到它们
显然上面的代码在不正确,但你知道该怎么做。
Did you have a look at django's Models' methods? You can find them here
Obviously the code above in incorrect, but you know what to do.
您可以简单地在日期范围上使用过滤器,使用 __gt(大于)和 __lt(小于)运算符:
或者您可以将学期写入数据库,例如您可以覆盖默认的 save() 方法,以便自动完成每当您保存新的或现有的事件时。所以模型是:
然后你可以简单地查询 Event.objects.filter(semester = 'spring')
You can simply use filter on a date range, using __gt (greater than) and __lt (less than) operators:
Or you can write the semester into the db, you can for instance override the default save() method so this is done automatically whenever you save a new or existing event. So the model would be:
Then you can simple query Event.objects.filter(semester = 'spring')