Django .order_by -day

时间:2014-09-09 23:29:45

标签: django django-views django-templates

我有一个模板标签,它返回一个节目列表:

def get_all_shows():

allshows = Shows.objects.all().order_by("-broadcast_day", "-broadcast_time")[:9].reverse()
tags = Shows.tags.all()
return {'allshows': allshows, 'tags': tags}

在我的模特中有一个日期选择字段:

class Shows(models.Model):
CHOICES = (
    ('Monday', 'Monday'),
    ('Tuesday', 'Tuesday'),
    ('Wednesday', 'Wednesday'),
    ('Thursday', 'Thursday'),
    ('Friday', 'Friday'),
    ('Saturday', 'Saturday'),
    ('Sunday', 'Sunday'),

)
broadcast_day = models.CharField(default=1,max_length=12, choices=CHOICES, blank=True)
broadcast_time = models.TimeField(default=datetime.now, blank=True)

我的问题是如何在白天订购我的清单,以便最近的一天显示相应的节目?

还有可能计算当天的日期吗?

感谢。

1 个答案:

答案 0 :(得分:0)

如果我正确地理解了你的问题,你需要使用Django Custom Model Manager
Models.py

class ShowManager(models.Manager):
    def my_custom_method(self):
         #some customizations !
         return super(ShowManager, self).my_custom_method().filter(#some filters here)

class Show(models.Model):
       CHOICES = (
         ('Monday', 'Monday'),
         ('Tuesday', 'Tuesday'),
         ('Wednesday', 'Wednesday'),
         ('Thursday', 'Thursday'),
         ('Friday', 'Friday'),
         ('Saturday', 'Saturday'),
         ('Sunday', 'Sunday'),

         )
       objects = models.Manager()
       my_customization = ShowManager()
       broadcast_day = models.CharField(default=1,max_length=12, choices=CHOICES, blank=True)
       broadcast_time = models.TimeField(default=datetime.now, blank=True)

现在你可以使用, Show.my_customization ! (比如Show.objects.all())在你的视图中!