如何在编辑对象时过滤django管理页面中下拉字段的内容? 例如:
class Question(models.Model):
creator = models.ForeignKey(User)
body = models.CharField(max_length=200)
category = models.ForeignKey(Category)
class Category(models.Model):
name = models.CharField(max_length=200)
creator = models.ForeignKey(User)
class QuestionAdmin(TeacherModelAdmin):
fieldsets = [
(None, {'fields': ['body', 'category']}),
]
#Filter by request.user == creator ?
答案 0 :(得分:0)
您可以在管理
中覆盖formfield_for_foreignkey
方法
class QuestionAdmin(TeacherModelAdmin):
def formfield_for_foreignkey(self, db_field, request, **kwargs):
if db_field.name == "category":
kwargs["queryset"] = Category.objects.filter(creater=request.user)
return super(QuestionAdmin, self).formfield_for_foreignkey(db_field, request, **kwargs)
答案 1 :(得分:0)
看起来似乎有没有官方方式。
但是,您可以使用BaseModelAdmin
中定义并由ModelAdmin
继承的Swiper API挂钩。解决方案看起来像这样:
class QuestionAdmin(TeacherModelAdmin):
fieldsets = [
(None, {'fields': ['body', 'category']}),
]
def get_field_queryset(self, db, db_field, request):
# Bahaviour for your field
if db_field.name == 'category':
return db_field.remote_field.model.filter(creator=request.user)
# Default behaviour unchanged
return super(OrderAdmin,self).get_field_queryset(db, db_field, request)
在应用此解决方案之前,如果您真的需要它,请三思而后行,不要成为官方API的一部分意味着当有人更改此挂钩而不提前添加弃用警告时,您可能会遇到麻烦。