Home > Enterprise >  How to use model's field's distinct values as select field's choices
How to use model's field's distinct values as select field's choices

Time:05-22

My model looks like this.

class Student(models.Model):
    user = models.OneToOneField(CustomUser, on_delete=models.CASCADE)
    roll_no = models.CharField(max_length=32)
    course = models.CharField(max_length=120)

Now I want to make a filter form using django_filters and want to use distinct values of course field as choices of select input but it requires each value to be associated with unique id and this field doesn't have any unique id. I tried this:

class StudentFilter(django_filters.FilterSet):
    course = django_filters.ModelChoiceFilter(queryset=Student.objects.values("course",flat = True).distinct(),empty_label=('Course'))
    class Meta:
         model = Student
         fields = []

but it didn't work.

Note I do not want to make separate model for course.

CodePudding user response:

The AllValuesFilter does exactly what you are asking for I believe

class StudentFilter(django_filters.FilterSet):
    course = django_filters.AllValuesFilter(field_name="course")
    
    class Meta:
         model = Student
         fields = []
  • Related