Django ForeignKey limit_choices_to a different ForeignKey id

后端 未结 3 1689
囚心锁ツ
囚心锁ツ 2020-12-15 08:58

I\'m trying to limit Django Admin choices of a ForeignKey using limit_choices_to, but I can\'t figure out how to do it properly.

This code does what I want if the ca

3条回答
  •  -上瘾入骨i
    2020-12-15 09:47

    Another approach, if you don't want to add a custom ModelForm, is to handle this in your ModelAdmin's get_form() method. This was preferable for me because I needed easy access to the request object for my queryset.

    class StoryAdmin(admin.ModelAdmin):
    
        def get_form(self, request, obj=None, **kwargs):
            form = super(StoryAdmin, self).get_form(request, obj, **kwargs)
    
            form.base_fields['local_categories'].queryset = LocalStoryCategory.\
                objects.filter(office=request.user.profile.office)
    
            return form
    

提交回复
热议问题