[Fixed]-Django filter in ModelForm with specific models

1👍

Your __init__ could look something like this:

def __init__(self, box_nr=None, *args, **kwargs):
    super(ReportForm, self).__init__(*args, **kwargs)

    qs = Product.objects.filter(item__box__box__box_code=box_nr)
    self.fields['product'].queryset = qs

Basically, you need a reverse lookup on Product to Item. You can read the relevant documentation here

Note that: item__box__box__box_code=box_nr is based on my understanding of your models. item__box does the reverse lookup. Rest might need some tweaking based on your model definitions.

Leave a comment