How to query so that a field of a model will show up instead of the actual model

Viewed 35

I am trying to query so that the value for a field in each model instance will show up with no duplicates. All of this is happening within the form:

class OrganisorClassStatusUpdateForm(forms.ModelForm):
    def __init__(self, *args, **kwargs):
        super(OrganisorClassStatusUpdateForm, self).__init__(*args, **kwargs)
        self.fields['off_day_student'] = forms.ModelChoiceField(
            queryset= Class.objects.filter(teacher=self.instance.teacher).filter(is_new_set=True).filter(time=self.instance.time).order_by('-date')[:10]
        )

Here, self.instance is referring to a Class model instance I am updating with this form. However, with this code, I would receive a list of Class instances for one of the form fields. What I want is a list of Student corresponding to each Class instances in the form field (there is only one student for each class). Therefore, instead of Class1, Class2, Class3, I would like to have Student1, Student2, Student3. Moreover, if there are any duplicates of a student's name, I would like to show only one. I hope the students are also listed in the order of -date for the classes as shown in the above code. Please ask me any questions. Thanks a lot.

Here is the Class Model as some of you have asked:

class Class(models.Model):
    teacher = models.ForeignKey('Agent', null=True, blank=True, on_delete=models.SET_NULL)
    student = models.ForeignKey('Lead', null=True, blank=True, on_delete=models.SET_NULL, related_name='student')
1 Answers

In that case try to generate the queryset from Lead/Student, and use your existing Class filter against the related_name:

queryset = Lead.objects.filter(
    student__in=Class.objects.filter(
        teacher=self.instance.teacher,
        is_new_set=True,
        time=self.instance.time,
    )[:10]
).order_by('-student__date')

If you are using Postgres, you can call distinct with the field name you want, like: .distinct('name')

Related