如何从模型方法返回字符串



使用以下模型,如果BreadSchedule对象的days_available等于一周中的每一天,我如何返回字符串"Baked fresh every day"?

我希望能够在我的模板(即item.is_available_daily)中调用它。

class Item(models.Model):
   name = models.CharField(max_length='250', help_text='Limited to 250 characters.')
class BreadSchedule(models.Model):
    bread = models.ForeignKey(Item)
    days_available = models.ManyToManyField('Day')
    class Meta:
        verbose_name_plural = 'Bread schedules'
    def __unicode__(self):
        return unicode(self.bread)
    def is_available_daily(self):
        "Returns whether a bread is available every day of the week."
        full_week = ['Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday', 'Sunday']
        if self.days_available.all() == full_week:
            return 'Baked fresh every day'
class Day(models.Model):
    day = models.CharField(max_length=50, help_text='Limited to 50 characters.')
    def __unicode__(self):
        return unicode(self.day)

在模板中调用不需要参数的方法。

{{ item.is_available_daily }}

要获得物品模型的信息,请使用items.readschedule_set.

class Item(models.Model):
    def is_available_daily(self):
        if self.breadschedule_set.all().count() == 7:
            return 'Baked fresh every day'

我会将日期列表和可用日期转换为集合:

def is_available_daily(self):
    full_week = set(['Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday', 'Sunday'])
    days_available = set(day.day for day in self.days_available.all())
    return days_available == full_week

我最终将方法更改为更简单的方法:

def is_available_daily(self):
    "Returns whether a bread is available every day of the week."
    if self.days_available.count() == 7:
        return 'Baked fresh every day'

然后,在模板中:{% if bread.is_available_daily %}{{ bread.is_available_daily }}{% endif %}

相关内容

  • 没有找到相关文章

最新更新