使用以下模型,如果BreadSchedule对象的days_available等于一周中的每一天,我将如何返回字符串'每天新鲜烘焙'?
我希望能够在我的模板中调用它(即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)
答案 0 :(得分:3)
在模板中调用不需要参数的方法。
{{ item.is_available_daily }}
要获取物品模型的信息,请使用items.breadschedule_set。
class Item(models.Model):
def is_available_daily(self):
if self.breadschedule_set.all().count() == 7:
return 'Baked fresh every day'
答案 1 :(得分:0)
我会将日期列表和可用日期分为几组:
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
答案 2 :(得分:0)
我最终将方法更改为更简单的方法:
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 %}