0

Using the following model, how would I return a string 'Baked fresh every day' if the BreadSchedule object had days_available equal to every day of the week?

I want to be able to call this in my template (i.e. 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)
Patrick Beeson
  • 1,667
  • 21
  • 36

3 Answers3

3

Methods that require no arguments are called in the template.

{{ item.is_available_daily }}

To get the information to your Item model use the items.breadschedule_set.

class Item(models.Model):

    def is_available_daily(self):
        if self.breadschedule_set.all().count() == 7:
            return 'Baked fresh every day'
kanu
  • 726
  • 5
  • 9
0

I would turn the list of days and the available days into sets:

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
RemcoGerlich
  • 30,470
  • 6
  • 61
  • 79
0

I ended up changing the method to something simpler:

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'

Then, in the template: {% if bread.is_available_daily %}{{ bread.is_available_daily }}{% endif %}

Patrick Beeson
  • 1,667
  • 21
  • 36