I'm trying to write some custom methods for my models but I'm getting the following error:
Attribute Error: 'ForeignRelatedObjectsDescriptor' object has no attribute all|filter
This happens when I run this code:
chore = Chore(name='Laundry') chore.schedule_set.create(week_day='monday', time_due='17:30:00') chore.scheduled()
Does anyone have any advice on how to make this work or what I might be missing? I've checked the Django documents but they seem to only cover the most basic uses of models.
models.py:
from django.db import models from datetime import date, timedelta class ChoreManager(models.Manager): def by_day(self, week_day): if week_day == 'today': week_day = date.today().strftime("%A") chores = self.filter(week_day=week_day) if chores.count() > 0: return chores else: return False def today(self): return self.by_day(week_day='today') class Chore(models.Model): chores = ChoreManager() name = models.CharField(max_length=50) notes = models.TextField(null=True) def scheduled(self, week_day=None): if week_day is None: schedule_count = Chore.schedule_set.all().count() else: if week_day == 'today': week_day = date.today().strftime("%A") schedule_count = Chore.schedule_set.filter(week_day=week_day).count() if schedule_count > 0: return True else: return False def times_by_day(self, week_day): if self.scheduled() == True: if week_day == 'today': week_day = date.today().strftime("%A") return Chore.schedule_set.filter(week_day=week_day).values('time_due') else: return False class Schedule(models.Model): chore = models.ForeignKey('Chore') week_day = models.CharField(max_length=9) time_due = models.TimeField() def mark_complete(self): completed_event = Schedule.completedevent_set.create() completed_event.save() def completed_this_week(self): today = date.today() weekstart = today - timedelta(days=today.weekday()) weekend = weekstart + timedelta(days=7, hours=23, minutes=59, seconds=59) if Schedule.completedevent_set.filter(datetime_completed__gte=weekstart, datetime_completed__lte=weekend).count() > 0: return True else: return False class CompletedEvent(models.Model): schedule = models.ForeignKey('Schedule') datetime_completed = models.DateTimeField(auto_now_add=True)
change:
schedule_count = Chore.schedule_set.all().count()
to:
schedule_count = self.schedule_set.all().count()
in all the occurrences..
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With