我正在尝试为我的模型编写一些自定义方法,但是我收到以下错误:
Attribute Error: 'ForeignRelatedObjectsDescriptor' object has no attribute all|filter
当我运行此代码时会发生这种情况:
chore = Chore(name='Laundry') chore.schedule_set.create(week_day='monday', time_due='17:30:00') chore.scheduled()
有没有人对如何完成这项工作或我可能缺少什么有任何建议?我检查了Django文档,但它们似乎只涵盖了模型的最基本用途。
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)
答案 0 :(得分:12)
改变:
schedule_count = Chore.schedule_set.all().count()
为:
schedule_count = self.schedule_set.all().count()
在所有事件中..