我有一个模型 Course,它是 Group 模型的子类。如何以类似于他所有组的方式访问用户课程(例如request.user.courses
)?
问问题
361 次
1 回答
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
您需要通过模型继承生成的 OneToOneField 在和之间获取组然后获取课程Course
。
不知道你为什么子类化Group
. 你也可以
class Course(models.Model):
students = models.ManyToManyField(User, related_name='courses')
如果你真的想扩展User
拥有User.courses
like 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')
于 2012-04-14T04:44:23.117 回答