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

前端 未结 4 1492
南旧
南旧 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:40

    class SchoolAdminForm(forms.ModelForm):
        students = forms.ModelMultipleChoiceField(
            queryset=Student.objects.all(),
            widget=FilteredSelectMultiple(verbose_name='students', is_stacked=False))
    
        class Meta:
            model = School
            fields = ['your_school_fields_go_here']
    
        def __init__(self, *args, **kwargs):
            super(SchoolAdminForm, self).__init__(*args, **kwargs)
            if self.instance:
                # fill initial related values
                self.fields['students'].initial = self.instance.student_set.all()
    
    class SchoolAdmin(admin.ModelAdmin):
       form = SchoolAdminForm
    
       def save_model(self, request, obj, form, change):
           original_students = obj.student_set.all()
           new_students = form.cleaned_data['students']
           remove_qs = original_students.exclude(id__in=new_students.values('id'))
           add_qs = new_students.exclude(id__in=original_students.values('id'))
           for item in remove_qs:
               obj.student_set.remove(item)
           for item in add_qs:
               obj.student_set.add(item)
           obj.save()
    

提交回复
热议问题