在此项目中,我们为教室中的学生分配了徽章。
class Badge(models.Model):
klass = models.ForeignKey( # klass means classroom
'klass.Class',
on_delete=models.CASCADE,
related_name='badges',
db_index=True,
)
users = models.ManyToManyField( # the students in 'klass' that have this badge
User,
through='UserBadge',
through_fields=('badge', 'user'),
)
users
ManyToMany字段的自定义中间表:
class UserBadge(models.Model):
user = models.ForeignKey(
User,
on_delete=models.CASCADE,
related_name='taken_badges',
)
badge = models.ForeignKey(
Badge,
on_delete=models.CASCADE,
related_name='assigned_badges',
)
klass = models.ForeignKey( # this classroom is badge.klass
'klass.Class',
on_delete=models.CASCADE,
related_name='assigned_badges',
)
我需要找到与特定user
和klass
相关的所有徽章。这样我就可以检索特定教室中特定学生的所有徽章。
我尝试过:
Bagde.objects.filter(userbadge__user__id = student_id,userbadge__klass__id=klass_id)
,错误是:
Cannot resolve keyword 'userbadge' into field.
谢谢。
答案 0 :(得分:1)
由于您将related_name
设置为'assigned_badges'
,因此应将过滤器实现为:
Bagde.objects.filter(
assigned_badges__user__id=student_id,
assigned_badges__klass__id=klass_id
)