Django模板和数据库查询中的自定义方法

时间:2015-01-16 17:34:15

标签: python django

我有一个简单的模型来显示公司的开放时间

class Company(Model):
    class Meta:
        verbose_name = _(u"Empresa")
        verbose_name_plural = _(u"Empresas")
        ordering = ('published_dt',)

    user = ForeignKey('auth.User', verbose_name=_(u"Responsável"), null=True, blank=True)
    category = ForeignKey(CompanyCategory, verbose_name=_(u"Categoria"), help_text=_(u"Categoria que a empresa faz parte. Eg:. Alimentação, Pet Shop"), null=True, blank=True)

    # Company Fields
    title = CharField(max_length=150, verbose_name=_(u"Nome da Empresa"), null=True, blank=True)
    slogan = CharField(max_length=150, verbose_name=_(u"Slogan"), help_text=_(u"Um slogan ou descrição curta. Ex:. 'Compramos sua moto e pagamos á vista'"), null=True, blank=True)
    image = ImageField(blank=True, null=True, upload_to='uploaded_images')
    crop = CharField(choices=CROP, max_length=200, null=True, blank=True, verbose_name=_(u"Cortar Imagem"), help_text=_(u"Selecione o ponto de referência para cortarmos a imagem."))
    email = EmailField(max_length=200, verbose_name=_(u"Email"), null=True, blank=True)
    website = URLField(max_length=200, verbose_name=_(u"Website"), null=True, blank=True)
    published = BooleanField(default=True, verbose_name=_(u"Publicado"))
    published_dt = DateTimeField(null=True, blank=True, default=datetime.now(), help_text=_(u"Date of publication - Not necessary to complete if you do not know what it is."), verbose_name=_(u"Published Date"))
    description = HTMLField(null=True, blank=True, verbose_name=_(u"Descrição"), help_text=_(u"Uma descrição da sua empresa em poucas linhas."))

    enable_comments = BooleanField(default=True, verbose_name=_(u"Habilitar Comentários"))
    # Admin fields
    slug = SlugField(verbose_name=_(u'Slug / URL'), blank=True, null=True, max_length=300,)
    order = PositiveIntegerField(verbose_name=_(u"Ordem"), null=True, blank=True)

    def __unicode__(self):
        return u'%s' % self.title

    def get_address(self):
        if self.address and self.city and self.number and self.uf:
            return u'%s, %s - %s, %s' % (self.address, self.number, self.city, self.uf)

    def get_absolute_url(self):
        code = codifica(self.pk)
        return reverse('website:company_detail', kwargs={'slug':self.slug, 'pk':self.pk})

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)

我需要一种方法在我的模板上添加{{ company.is_open }}Company.objects.all().order_by('open')。我怎么能用我的结构呢?

1 个答案:

答案 0 :(得分:2)

向公司添加方法:

import datetime

...

class Company(Model):

    ...

    def is_open(self):
        today_hours = self.opening_times.filter(weekday=datetime.datetime.today().weekday())[0] # you may want to add code to make sure that there is an entry for this weekday
        if datetime.datetime.now().time() > today_hours.fromHour and datetime.datetime.now().time() < today_hours.toHour:
            return True
        else:
            return False

然后,您就可以使用模板中的{{ company.is_open }}来调用此内容。

不幸的是,您无法在数据库调用中查询此订单或按订单查询。但是,您可以在查询完成后对其进行排序:

companies = sorted(Company.objects.all(), key=lambda c: c.is_open(), reverse=True)