关于python:在模型定义中过滤相关模型的问题

An issue filtering related models inside the model definition

我正在尝试为我的模型编写一些自定义方法但是我收到以下错误:

Attribute Error: 'ForeignRelatedObjectsDescriptor' object has no attribute all|filter

运行此代码时会发生这种情况:

1
2
3
chore = Chore(name='Laundry')
chore.schedule_set.create(week_day='monday', time_due='17:30:00')
chore.scheduled()

有没有人对如何做这项工作或我可能缺少什么有任何建议? 我检查了Django文档,但它们似乎只涵盖了模型的最基本用途。

models.py:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
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)

更改:

1
schedule_count = Chore.schedule_set.all().count()

至:

1
schedule_count = self.schedule_set.all().count()

在所有发生..