select a valid Choice While using ModelChoiceField and queryset

I used
And inside it i used queryset.
I also used .values_list()

And so that’s your answer.

You write your query to return the data elements needed for the select box, and use that as the choices attribute of the ChoiceField.

So basically , i need to run a query outside the ChoiceField ?

That’s really going to depend upon how “dynamic” those choices are going to be. If those choices are static, you can use the query in exactly the same way you were trying to use it in the ModelChoiceField.

However, if the choices are going to change, then yes. You would put that query in a function, and reference the function as the choices attribute.

Again quoting directly from the docs for ChoiceField.choices:

Either an iterable of 2-tuples to use as choices for this field, enumeration choices, or a callable that returns such an iterable.

(Emphasis added)

1 Like

Can you show me a way to write that function ?
I think i need to append it inside a loop , i suppose
I m not sure though

Play with the query inside the Django shell - that’s the easiest way to experiment with queries you’re not familiar with.

1 Like

I ll give it a swing and come back to you .

Thanks for the Help !.
got the answer finally.

choice1 = []
for y in place.objects.values_list('placeName', flat=True):

Inside The Class

 d1sight =  forms.ChoiceField(choices= choice1, required= False)

It’s great to fix your issue by the end of the day.
But I’ll suggest to mark answer to the (post of “Ken”) which consider as a help for you to find a solution to your issue, because he gave you the guide to find your answer, and without his help you were still searching for an answer.

Yes true, but all of his statements are a step towards the answer , i was confused which one to mark , that why i wrote a thank you note with the solution

Side note:

You didn’t need to go through this:

Like when you wrote this earlier:

Means you could have just as easily used this for this purpose here:

return place.objects.values_list('placeName', 'placeName')
1 Like