假设我的模型看起来像这样:
class MyOtherModel(model.Model):
name = CharField(max_length=50)
type = CharField(max_length=5, default='A')
class MyModel(models.Model):
name = CharField(max_length=50)
some_m2m = ManyToManyField('MyOtherModel')
并且,在管理员中,我希望它根据类型拆分MyOtherModel
个实例,以显示在屏幕的不同部分,或者使用不同的标签或其他任何内容。
我希望能够做到这样的事情(就像你可以使用ModelAdmin的list_display
属性一样):
class MyModelAdmin(admin.ModelAdmin):
model = MyModel
fieldsets = [
(None, {
'fields': [
('name', 'some_m2m_type_A', 'some_m2m_type_B',)
]
})
]
def some_m2m_type_A(self):
return MyOtherModel.objects.filter(type='A')
def some_m2m_type_B(self):
return MyOtherModel.objects.filter(type='B')
很明显,它不会起作用,但你明白了。
我尝试覆盖formfield_for_manytomany()
:
def formfield_for_manytomany(self, db_field, request=None, **kwargs):
if db_field == 'some_m2m_type_A':
kwargs["queryset"] = MyOtherModel.objects.filter(type='A')
elif db_field == 'some_m2m_type_B':
kwargs["queryset"] = MyOtherModel.objects.filter(type='B')
return super(MyModelAdmin, self).formfield_for_manytomany(db_field, request, **kwargs)
类似于this question中的建议,但Django仍然出错:
FieldError:未知字段(some_m2m_type_A,some_m2m_type_B) 为MyModel指定。检查字段/字段集/排除类的属性 MyModelAdmin。
并且在调用formfield_for_manytomany()
...
有没有一种简单的方法可以完成我在Django Admin中的操作?或者它是否需要大规模的改革,重写模板以及其他难以维护的hackery?
答案 0 :(得分:0)
您可以通过模型定义自己的;
class MyOtherModel(model.Model):
name = CharField(max_length=50)
type = CharField(max_length=5, default='A')
class MyModel(models.Model):
name = CharField(max_length=50)
some_m2m = ManyToManyField('MyOtherModel', through='MyThroughModel')
class MyThroughModel(models.Model):
mymodel = models.ForeignKey(MyModel)
myothermodel = models.ForeignKey(MyOtherModel)
然后在admin.py
;
class MyOtherModelAdmin(admin.ModelAdmin):
model = MyOtherModel
list_filter = ['mythroughmodel_set__myothermodel__type']