Listing only usable values in OneToOneField Django

前端 未结 2 1500
被撕碎了的回忆
被撕碎了的回忆 2021-01-16 07:33

I want to list only usable items in OneToOneField not all items, its not like filtering values in ChoiceField because we need to find out only values which can be used which

2条回答
  •  挽巷
    挽巷 (楼主)
    2021-01-16 07:58

    You need something like this in the init() method of your form.

    def __init__(self, *args, **kwargs):
    
        super(BarForm, self).__init__(*args, **kwargs)
    
        # returns Bar(s) who are not in Foo(s).
        self.fields['foo'].queryset = Bar.objects.exclude(id__in=Foo.objects.all().values_list(
                'bar_id', flat=True))
    

    PS: Code not tested.

提交回复
热议问题