使用 ManyToMany 字段交换 ForeignKey 时出现异常
Exception when swapping a ForeignKey with ManyToMany Field
我将 ForeignKey 关系更改为 ManyToMany relationship.Does 更新方法在多对多上工作后出现以下错误?
Cannot update model field
(only
non-relations and foreign keys permitted).
现在,当试图保存 modelStudent
model.This 是我将其字段更改为 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) 中的内容。基本上这种形式的目的是允许用户将多个学生分配给管理员中的模型患者 interface.I 仍然喜欢该功能
图表 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)
简而言之,为什么我会收到
的错误
Cannot update model field
(only
non-relations and foreign keys permitted).
在我尝试保存模型时在我的管理应用程序中,因为我已将 ForeignKey
更改为 ManyToMany
relationship.Any 关于如何解决此问题的建议?
已解决问题。问题是 django 不支持 manytomany 字段的批量更新
通过以下方式解决了这个问题
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
我将 ForeignKey 关系更改为 ManyToMany relationship.Does 更新方法在多对多上工作后出现以下错误?
Cannot update model field (only non-relations and foreign keys permitted).
现在,当试图保存 modelStudent
model.This 是我将其字段更改为 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) 中的内容。基本上这种形式的目的是允许用户将多个学生分配给管理员中的模型患者 interface.I 仍然喜欢该功能
图表 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)
简而言之,为什么我会收到
的错误Cannot update model field (only non-relations and foreign keys permitted).
在我尝试保存模型时在我的管理应用程序中,因为我已将 ForeignKey
更改为 ManyToMany
relationship.Any 关于如何解决此问题的建议?
已解决问题。问题是 django 不支持 manytomany 字段的批量更新
通过以下方式解决了这个问题
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