Search code examples
pythondjangodjango-admindjango-ormdjango-model-field

Exception when swapping a ForeignKey with ManyToMany Field


I am getting the following error after I changed a ForeignKey relation to a ManyToMany relationship.Does update method work on Many to Many ?.

Cannot update model field (only non-relations and foreign keys permitted).

Now this happens in the admin section when attempting to save a modelStudent model.This is the model whose field I changed to ManytoMany

Exhibit 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)

Now this is what I have in my admin section (admin.py). Basically the purpose of this form was to allow the user to assign multiple students to a modelPatient in the admin interface.I would still like that feature

Exhibit 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

and then this is the registered interface

Exhibit 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)

Then I register the model as this:

admin.site.register(modelStudent,modelStudentAdmin)

In short why am I getting an error of

Cannot update model field (only non-relations and foreign keys permitted).

in my admin application when I attempt to save the model since I have changed a ForeignKey to ManyToMany relationship.Any suggestions on how I can resolve this ?


Solution

  • Fixed the problem. The problem is django does not support bulk update for manytomany fields source

    Fixed this in the following way

    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