python – django admin – 选择反向外键关系(不创建,我想添加可用)

让我们说我有一个模范学校和另一个模特学生.

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

在管理员中单击学校时,将显示一个显示学校模型字段和值的新页面.

我还想在该页面中选择已有的学生列表.

内联是不同的,它们将允许创建和编辑属于该学校的新记录(学生).但我不想这样,假设已经有很多学生记录可用.我应该可以在该学校模型页面的管理员中选择它们.

最佳答案
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()

转载注明原文:python – django admin – 选择反向外键关系(不创建,我想添加可用) - 代码日志