我想为以下值和模型创建一个filter-sort mixin:
class Course(models.Model):
title = models.CharField(max_length=70)
description = models.TextField()
max_students = models.IntegerField()
min_students = models.IntegerField()
is_live = models.BooleanField(default=False)
is_deleted = models.BooleanField(default=False)
teacher = models.ForeignKey(User)
class Session(models.Model):
course = models.ForeignKey(Course)
title = models.CharField(max_length=50)
description = models.TextField(max_length=1000, default='')
date_from = models.DateField()
date_to = models.DateField()
time_from = models.TimeField()
time_to = models.TimeField()
class CourseSignup(models.Model):
course = models.ForeignKey(Course)
student = models.ForeignKey(User)
enrollment_date = models.DateTimeField(auto_now=True)
class TeacherRating(models.Model):
course = models.ForeignKey(Course)
teacher = models.ForeignKey(User)
rated_by = models.ForeignKey(User)
rating = models.IntegerField(default=0)
comment = models.CharField(max_length=300, default='')
我想实现以下功能
您如何为此创建功能?
我尝试过使用
感谢任何tipp!
答案 0 :(得分:7)
除了使用Q对象进行高级AND / OR查询外,还要熟悉反向查找。
当Django为外键关系创建反向查找时。在您的情况下,您可以获得属于课程的所有会话,其中一种方式可以过滤。
c = Course.objects.get(id=1)
sessions = Session.objects.filter(course__id=c.id) # First way, forward lookup.
sessions = c.session_set.all() # Second way using the reverse lookup session_set added to Course object.
您还希望熟悉annotate()
和aggregate()
,这些允许您计算字段并对结果进行排序/过滤。例如,Count,Sum,Avg,Min,Max等
courses_with_at_least_five_students = Course.objects.annotate(
num_students=Count('coursesignup_set__all')
).order_by(
'-num_students'
).filter(
num_students__gte=5
)
course_earliest_session_within_last_240_days_with_avg_teacher_rating_below_4 = Course.objects.annotate(
min_session_date_from = Min('session_set__all')
).annotate(
avg_teacher_rating = Avg('teacherrating_set__all')
).order_by(
'min_session_date_from',
'-avg_teacher_rating'
).filter(
min_session_date_from__gte=datetime.now() - datetime.timedelta(days=240)
avg_teacher_rating__lte=4
)
Q用于允许您在查询中进行逻辑AND和逻辑OR。
答案 1 :(得分:4)
我建议您查看复杂的查找:https://docs.djangoproject.com/en/1.5/topics/db/queries/#complex-lookups-with-q-objects
以下查询可能不适用于您的情况(教师模型是什么样的?),但我希望它可以作为如何使用复杂查找的指示。
from django.db.models import Q
Course.objects.filter(Q(session__date__range=(start,end)) &
Q(teacher__rating__gt=3))
除非绝对必要,否则我确实会避免非规范化。
我的排序问题并不完全清楚。是否要显示按date_from过滤的课程,并按日期,名称进行排序?