django admin - select reverse foreign key relationships (not create, I want to add available)

前端 未结 4 1485
南旧
南旧 2021-02-14 02:09

Lets say I have a model School and another model Student.

class Student(models.Model):
   school = models.ForeignKey(School)
   name =          


        
4条回答
  •  名媛妹妹
    2021-02-14 02:46

    Do you mean that for a given School instance you want to be able to get a list of all the students related to that school?

    In which case you use the related_name attribute of the ForeignKey relationship you specified. You haven't defined the related_name where you do:

    school = models.ForeignKey(School)
    

    which is fine, it just uses the default related name which is the name of the child class (student) followed by _set

    so for your school instance:

    school = School.objects.get(pk=1)
    students = school.student_set.all()  # or .filter() or .exclude() etc
    

    then you can pass that student queryset into your template.

提交回复
热议问题