使用ManyToMany字段交换ForeignKey时出现异常

时间:2017-03-22 23:13:21

标签: python django django-admin django-orm django-model-field

在将ForeignKey关系更改为ManyToMany关系后,我收到以下错误。更新方法工作多对多吗?。

  

无法更新模型字段    (只要   允许非关系和外键)。

现在,在尝试保存modelStudent模型时,管理部分会发生这种情况。这是我将其字段更改为ManytoMany的模型

图表A:

class modelPatient(models.Model):
    #student            = models.ForeignKey(modelStudent ,null=True, blank=True ) #Mutlipe Patients for single student
    student            = models.ManyToManyField(modelStudent,null=True,default=None,blank=True)
    patient_name       = models.CharField(max_length=128, unique=False)

现在这就是我在管理部分(admin.py)中的内容。基本上这个表单的目的是允许用户将多个学生分配到管理界面中的modelPatient。我仍然喜欢该功能

图表B:

class adminStudentForm(forms.ModelForm):
    class Meta:
        model = modelStudent
        fields = '__all__'
    patients = forms.ModelMultipleChoiceField(queryset=modelPatient.objects.all())

    def __init__(self, *args, **kwargs):
        super(adminStudentForm, self).__init__(*args, **kwargs)
        if self.instance:

            self.fields['patients'].initial = self.instance.modelpatient_set.all()

    def save(self, *args, **kwargs):
        try:
            instance = super(adminStudentForm, self).save(commit=False)
            self.fields['patients'].initial.update(student=None) <-------EXCEPTION HERE
            self.cleaned_data['patients'].update(student=instance)
        except Exception as e:
            print(e)
        return instance

然后这是注册的界面

图表C:

class modelStudentAdmin(admin.ModelAdmin):
    form = adminStudentForm
    search_fields = ('first_name','user__username')
#What records to show when the model is clicked in the admin
#The super user should get everything and staff should get limited data
def get_queryset(self, request):
    qs = super(modelStudentAdmin, self).get_queryset(request)

    if request.user.is_superuser:
        return qs
    else:
        # Get the school instance
        # Only show the students that belong to this school
        schoolInstance = modelSchool.objects.get(user=request.user)
        qs = modelStudent.objects.filter(school=schoolInstance)
        return qs

#Limit the no. of options of Foreign Key that could be assigned
def formfield_for_foreignkey(self, db_field, request, **kwargs):
    if request.user.is_superuser:
        return super(modelStudentAdmin, self).formfield_for_foreignkey(db_field, request, **kwargs)

    #Not superuser only staff
    #Check what fields to pull out for field school
    if db_field.name == 'school':
        kwargs['queryset'] =  modelSchool.objects.filter(user=request.user)

    # Check what fields to pull out for field user
    elif db_field.name == 'user':
        t = modelSchool.objects.filter(user=request.user)
        kwargs['queryset'] = User.objects.filter(modelschool=t)

    return super(modelStudentAdmin,self).formfield_for_foreignkey(db_field, request, **kwargs)

然后我将模型注册为:

admin.site.register(modelStudent,modelStudentAdmin)

简而言之,为什么我会收到错误

  

无法更新模型字段    (只要   允许非关系和外键)。

当我尝试保存模型时,在我的管理应用程序中

,因为我已将ForeignKey更改为ManyToMany关系。有关如何解决此问题的任何建议?

1 个答案:

答案 0 :(得分:0)

修正了问题。问题是django不支持批量更新多个字段source

通过以下方式解决此问题

def save(self, *args, **kwargs):
    try:
        instance = super(adminStudentForm, self).save(commit=False)
        patients_qset = self.cleaned_data['patients']
        for pqset in patients_qset:
            pqset.student.add(instance)

    except Exception as e:
        print(e)
        raise
    return instance