0

在我的模型中,我有:

class StudentProfile(models.Model):
    # Relational fields
    #more fields
    sports_assigned = models.ManyToManyField('Sport', through="StudentSportAssociation")

我的模型形式如下:

class UpdateStudentForm(ModelForm):
    def __init__(self, *args, **kwargs):
        super(UpdateStudentForm, self).__init__(*args, **kwargs)
    class Meta:
        model = StudentProfile
    sports_assigned = forms.ModelMultipleChoiceField(queryset=SportWithLevel.objects.all(),
                                                     widget=FilteredSelectMultiple("Select", is_stacked=False), required=True)

通过表是:

class StudentSportAssociation(AbstractBaseModel):
    """
    Association of student to a sport and his current level in the sport
    """
    sport = models.ForeignKey('Sport')
    level = models.ForeignKey('Level')
    student = models.ForeignKey('StudentProfile', related_name="sports_with_levels")
    # save and all follows

现在我需要访问

学生体育协会

访问表单时“通过”表。现在它从 Sport 模型中获取值。有什么办法可以打破这种正常的方式并从直通表中获取详细信息吗?

4

1 回答 1

0

查看 django 文档的这一部分: https ://docs.djangoproject.com/en/1.4/topics/db/models/#extra-fields-on-many-to-many-relationships 。尤其是阅读最后两个例子。它们描述了如何获取中间对象。

总结一下,你有2个选择:

1.通过单独的查询获取中间模型

StudentSportAssociation.objects.filter(student=student_profile_instance)

2.你查询多对多的反向关系。在你的情况下:

student_profile_instance.sports_with_levels.all()

“sports_with_levels”,因为您定义了一个related_name,如果您没有定义一个,它将是:

student_profile_instance.studentsportassociation_set.all()

默认情况下,Django 会在模型名称中添加一个“_set”。

于 2013-02-07T10:16:13.950 回答