Select2 and django_filters not querying foreign keys

Viewed 644

I'm using django_filters for an advanced search and select2Widget to display the options of a foreign key field.

The proper values load but whenever I submit the form I get an error message: Select a valid choice. That choice is not one of the available choices.

The error might seem pretty obvious but I can't find out how to solve it. Any suggestions?

filters.py

class MyFilter(django_filters.FilterSet):
    b = django_filters.ModelChoiceFilter(
        queryset=ModelA.objects.values_list('b__name', flat=True)
        widget=Select2Widget()
    )

class Meta:
    model = ModelA
    fields = ('b',)

models.py

class ModelA(models.Model):
    b = models.ForeignKey('ModelB', on_delete=models.CASCADE)

class ModelB(models.Model):
    name = models.CharField(max_length=100, unique=True)

    def __str__(self):
        return self.name
1 Answers

AS user @dirkgroten pointed out in a comment to the question, the following line looks strange:

queryset=ModelA.objects.values_list('b__name', flat=True)

This way the widget has no way of knowing the pk of each element of the list (since it only return the names). That might couse that the view cannot save a selected ModelB instance, since it does not know the selected pk.

Ah, you might also want to use ModelB instead of ModelA

Try changing it to something like this

queryset=ModelB.objects.values('pk', 'b__name')

or even this

queryset=ModelB.objects.all()

and let us know if that works.

Related