将 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
。关于如何解决这个问题的任何建议?