[Answer]-Creating select modelform based off min and max year present in table?

1👍

Thanks to lalo for pointing me in the right direction. I managed to figure it out using the following;

    years_list = []
choices = []
year_list = Post.objects.all().values_list('date_created').distinct()

for years_avail in year_list:
    years_list.append(years_avail[0].strftime('%Y'))

for year in years_list:
    choice =(year, year)
    choices.append(choice)

years = forms.ChoiceField(choices, label='') 

Is this a good way to go about doing this or is this inefficient/wrong?

👤Deep

0👍

ModelChoiceField is for model select, based in foreign key. I think you have to user ChoiceField and generate the options in runtime.

Show me where you use the form, maybe can show you how to do.

Leave a comment