[Django]-How do I populate a ModelChoiceField from two Models

5👍

I don’t think you can use a ModelChoiceField with two different models, because you cannot have a queryset composed by two different models.

You’d better try to use ChoiceField, which accepts a choices parameter with a list of tuples.

Say you have two models in models.py like this:

from django.db import models

class Model1(models.Model):
    name = models.CharField(max_length=20, primary_key=True)
    description = models.CharField(max_length=200)

class Model2(models.Model):
    name = models.CharField(max_length=20, primary_key=True)
    description = models.CharField(max_length=200)

You can create a Form like this in forms.py:

from django import forms

from .models import Model1, Model2

class MultipleModelChoiceForm(forms.Form):
    select = forms.ChoiceField(choices=[])

    def __init__(self, *args, **kwargs):
        super(MultipleModelChoiceForm, self).__init__(*args, **kwargs)
        choices = []
        for obj1 in Model1.objects.all():
            choices.append((obj1.name, obj1.description))
        for obj2 in Model2.objects.all():
            choices.append((obj2.name, obj2.description))
        self.fields['select'].choices = choices

Note that choices are defined in the __init__ of the form, to have the select field updated with all records in Model1 and Model2 when you create an instance of the form.

Leave a comment