我的模型有manytomany字段,在我的AdminModel类的管理面板中,我使用此代码:
def get_object(self, request, object_id, to_field):
# Hook obj for use in formfield_for_manytomany
self.obj = super(GoalAdmin, self).get_object(request, object_id)
return self.obj
def formfield_for_manytomany(self, db_field, request, **kwargs):
if db_field.name == "reviewers":
kwargs["queryset"] = Goal.objects.get(id=self.obj.id).reviewers.all()
return super(GoalAdmin, self).formfield_for_manytomany(db_field, request, **kwargs)
一切正常,直到我尝试从管理面板添加目标。比我收到这个错误:
'GoalAdmin' object has no attribute 'obj'
我该如何解决?
UPD:错误发生在这里:
kwargs["queryset"] = Goal.objects.get(id=self.obj.id).reviewers.all()
Variable Value
self <goals.admin.GoalAdmin object at 0xa7d472cc>
db_field <django.db.models.fields.related.ManyToManyField: reviewers>
request <WSGIRequest: GET '/goals/goal/add/'>
kwargs {}
答案 0 :(得分:3)
您的错误可能正在发生,因为get_object
未在formfield_for_manytomany
运行时被调用。
可能有办法解决这个问题,但这确实是错误的做法。这种事情应该通过定义自定义表单并在管理类中使用它来完成。
class GoalAdminForm(forms.ModelForm):
def __init__(self, *args, **kwargs):
super(GoalAdminForm, self).__init__(*args, **kwargs)
if self.instance is not None:
self.fields["reviewers"].queryset = Goal.objects.get(id=self.instance.id).reviewers.all()
class GoalAdmin(admin.ModelAdmin):
form = GoalAdminForm