Lets say I have a model School
and another model Student
.
class Student(models.Model):
school = models.ForeignKey(School)
name =
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()