Преобразование QuerySet в список в Django для ModelMultipleChoiceField

TIMESLOT_LIST = (
        (5, '09:00 – 09:30'),
        (9, '09:30 – 10:00'),
        (2, '10:00 – 10:30'),
    )
    
class AvailabilitiesForm(forms.Form):
    time_slot = forms.ModelMultipleChoiceField(queryset = None, widget=forms.CheckboxSelectMultiple)

    def __init__(self, *args, **kwargs):
        date = kwargs.pop('date')
        super(AvailabilitiesForm, self).__init__(*args, **kwargs)
        #choices = getChoices(letter)
        self.fields['time_slot'].queryset = Appointment.objects.filter(date = date).values_list('time_slot', flat = True)

Отображается :

enter image description here

Я хочу :

enter image description here

Как я могу использовать TIMESLOT_LIST для отображения строки "9h00 - 9h30", а не 5?

Во время прохождения, как я могу вывести пункты пули?

вы можете сделать следующее:-

from django.utils.translation import gettext_lazy as _

class Appointment(models.Model):

    class TimeSlot(models.TextChoices):
        FIRST_T = '5', _('9:00 - 09:30')
        SECOND_T = '9', _('09:30 - 10:00')
        THIRD_T = '2', _('10:00 - 10:30')

    time_slot = models.CharField(max_length=1,choices=TimeSlot.choices,default=TimeSlot.FIRST_T)


class AvailabilitiesForm(forms.Form):
    time_slot = forms.MultipleChoiceField(widget=forms.CheckboxSelectMultiple)

    def __init__(self,*args,**kwargs):
        super().__init__(*args,**kwargs)
        d1 = kwargs.pop('date')
        ava_time = []

        for i in Appointment.objects.filter(date=d1):
            for x in Appointment.TimeSlot.choices:
                if x[0] == i.time_slot:
                    ava_time.append(x)

        self.fields['time_slot'].choices = ava_time
Вернуться на верх