我有一个模型,Course,它是Group模型的子类。如何以与其所有群组类似的方式访问用户课程(例如request.user.courses
)?
答案 0 :(得分:0)
尝试
qs = request.user.groups.filter(course__isnull=False)
for group in qs:
course = group.course
# or shortcuts
User.get_courses = lambda self: map(lambda g: g.course, self.groups.filter(course__isnull=False))
# or
User.get_courses = lambda self: Course.objects.filter(pk__in=self.groups.all())
# then
request.user.get_courses()
用户和课程之间没有直接关系。您需要通过跟踪由Group
和Course
之间的模型继承生成的OneToOneField来获取组然后获取课程。
不确定为什么要继承Group
。你也可以
class Course(models.Model):
students = models.ManyToManyField(User, related_name='courses')
如果您真的希望将User
扩展为User.courses
User.groups
,那么您可以
# Option 1
# in models.py
class UserCourse(models.Model):
user = models.ForeignKey(User)
course = models.ForeignKey(Course, db_column='group_id')
class Meta:
db_table = User.groups.through._meta.db_table
m2m = models.ManyToManyField(Course, related_name='students', through=UserCourse)
m2m.contribute_to_class(User, 'courses')
# Option 2
# simpler but has duplicated m2m table and different API
# Also a Course instance will not have corresponding
# Group instance in user.groups, which may not be correct in logic.
class UserCourse(models.Model):
user = models.ForeignKey(User, related_name='courses')
course = models.ForeignKey(Course)
# Option 3
# just as Option 2, but w/ M2M API
class UserCourse(models.Model):
user = models.ForeignKey(User)
course = models.ForeignKey(Course)
m2m = models.ManyToManyField(Course, related_name='students', through=UserCourse)
m2m.contribute_to_class(User, 'courses')