Reputation: 133
class Course(models.Model):
def is_active(self):
return self.enroll_set.count()>0
class CourseEvent(models.Model):
course = models.ForeignKey(Course)
I want to find all Events
that only point to active courses.
something like:
events = CourseEvent.objects.filter(course.is_active=True)
thank you
Upvotes: 0
Views: 73
Reputation: 6467
The answer is here: https://docs.djangoproject.com/en/dev/ref/models/querysets/#annotate
You make an annotation, it'll be filterable as a field.
It may look like this:
CourseEvent.objects.annotate(is_active=Count('course__enroll')).exclude(is_active=0)
Upvotes: 0
Reputation: 47222
Your is_active()
method makes no sense.
is_active
would imply a boolean of some sorts not 62. So there's something you can correct right off the bat. Normally, I would set a is_active
flag on the Course
model (thusly removing the method is_active
altogether) and toggle that making the ORM call really straight forward:
class Course(models.Model):
active = models.BooleanField(default=False)
events = CourseEvents.objects.filter(course__active=True)
Upvotes: 2