我正在尝试创建一个结构来显示食品公司的营业时间,按“营业”状态排序。但我不知道如何获取模板上的信息。例如:
#models.py
class Company(Model):
#... fields ...
def __unicode__(self):
return u'%s'%self.title
在这里,我将存储所有时间和日期。
class OpeningHours(Model):
class Meta:
verbose_name = _(u"Horário de Abertura")
verbose_name_plural = _(u"Horários de Abertura")
unique_together = ('company', 'weekday')
company = ForeignKey(Company, related_name="opening_times", verbose_name=_(u"Empresa"))
weekday = IntegerField(choices=WEEKDAYS, verbose_name=_(u"Dia da Semana"))
fromHour = TimeField(verbose_name=_(u"Abre ás:"), null=True, blank=True)
toHour = TimeField(verbose_name=_(u"Fecha ás:"), null=True, blank=True)
def __unicode__(self):
return "%s %s (%s - %s)" % (self.company, self.weekday, self.fromHour, self.toHour)
然后我在我的观点中捕获了所有这样的公司:
#views.py - This is how I'm processing the views
companies = sorted(Company.objects.filter(category__food=True).order_by('?')[0:4], key=lambda c: c.show_open(), reverse=True)
所以,现在问题出在模板中,我需要某种方式来捕捉这些信息:
template.html - 这是我需要在模板上做的
{% for company in companies %}
{% if company.open %}
OPEN
{% else %}
CLOSED
{% endif %}
<!-- I need to know when it's today, when it's tomorrow or when it's another day -->
{% ifequal company.open today %}
Next day will open is today at {{ company.next_time_open }}
{% ifequal company.open another_day %}
Next day will open is Sunday at {{ company.next_time_open }}
{% else %}
Wait, it's open right now from 22h till 00h
{% endif %}
{% endfor %}
请您参考如下方法:
首先,执行 .order_by('?') 是随机化您的查询集,然后您将在 Python 中对其进行排序。随机排序导致查询在数据库端需要更多的处理时间,然后在 Python 中排序是它自己的额外处理时间。我会考虑使用 Django 的方法对查询集进行排序,而不是通过在 .order_by() 中指定要排序的字段。
其次,减少数据库命中率的一种方法是在查询集上使用 .select_related()。这将在单个 SQL 语句下的查询集中包含相关模型,以便以后对模板中相关模型的调用不会导致新的数据库命中。
第三,在您的不同部分中有很多代码引用了我假设您已经定义的字段和方法,但如果没有直接看到它们,我无法判断您到底在做什么。目前无法给您更直接的答案。
