Search code examples
djangoformsdjango-modelsmodelchoicefield

Django :How can I let my modelChoiceField take two possible types of models


I need to let a modelChoiceField have the possiblity of taking two different models objects. for example can billnum take as queryset: facture_ventes.objects or facture_depc.objects at the same time instead of only one model :

billnum=forms.ModelChoiceField(queryset=facture_ventes.objects)

Thank You For your Help


Solution

  • I'm assuming that the models have the same fields. You may want to redesign your project so that you have one model and maybe an extra field on that model that differentiates between ventes and depc. This is my recommendation.

    Otherwise, you might be able to use a union query.

    billnum = forms.ModelChoiceField(
        queryset=facture_ventes.objects.union(facture_depc.objects.all())
    )
    

    Even then, somehow you would have to be able to distinguish between the pks of facture_ventes and facture_depc. It's too complicated. Change your model.