Best practice for Python typing out of dictionary (self.fields type in Django ModelForm)

Viewed 40

I have a form like this

class MerchantBrandsForm(forms.Form):
    brands = forms.ModelChoiceField(required=True, queryset=None)

    def __init__(self: merchant: Merchant, *args: Any, **kwargs: Any):
        super().__init__(*args, **kwargs)
        self.fields['brands'].queryset = merchant.brands.all()

But I have an error with mypy with the queryset as fields has a type Dict[str, Field], which cause error: "Field" has no attribute "queryset".

I know I can cast the fields using cast or ignore the typing, but I don't think this is a clean solution. What is the best way to assign brands queryset without ignoring the type or using cast function?

0 Answers
Related