Django filter_horizontal filtering

后端 未结 2 1081
野的像风
野的像风 2021-02-04 22:04

I have 2 models related by M2M type of relationship. I use filter_horizontal in the admin for editing my entities.

However, I would like to have a control o

相关标签:
2条回答
  • 2021-02-04 22:10

    This subject is always tricky in the Django admin. I suppose that in the inline defenition you can do something like this:

    class BAdmin(admin.TabularInline): ...

    def get_queryset(self, request):
        qs = super(BAdmin, self).get_queryset(request)
        return qs.filter(user=request.user)
    

    https://docs.djangoproject.com/en/stable/ref/contrib/admin/#django.contrib.admin.ModelAdmin.get_queryset

    0 讨论(0)
  • 2021-02-04 22:12

    I think I found it!

    class MyModelAdmin(admin.ModelAdmin):
    def formfield_for_manytomany(self, db_field, request, **kwargs):
        if db_field.name == "cars":
            kwargs["queryset"] = Car.objects.filter(owner=request.user)
        return super(MyModelAdmin, self).formfield_for_manytomany(db_field, request, **kwargs)
    

    ModelAdmin.formfield_for_manytomany(db_field, request, **kwargs)

    0 讨论(0)
提交回复
热议问题