On Aug 18, 2017 3:14 PM, "Jim Illback" <subaru...@hotmail.com> wrote:

Here’s a “problem” with migrations that I’ve had. It only occurs on a first
time installation (like a first-time upload to Heroku, for example).

In forms.py, I have a field dependent upon a column in another table
(Category):
    category = forms.TypedChoiceField(required=False, choices=[(category.pk,
category.name) for category in Category.objects.all()])


While the ModelChoiceField is more applicable to this issue, an alternative
for other scenarios is to use a callback function as the value for
choices=, for example:

#early in forms.py
def get_categories():
    return [(category.pk, category.name) for category in
Category.objects.all()]

# later in forms.py
category = forms.TypedChoiceField(required=False, choices=get_categories)

This has a similar effect to the ModelChoiceField, with the query only
running when the form is instantiated, but gives you the flexibility to use
whatever logic you'd like to come up with the choices for the field.

-James

-- 
You received this message because you are subscribed to the Google Groups 
"Django users" group.
To unsubscribe from this group and stop receiving emails from it, send an email 
to django-users+unsubscr...@googlegroups.com.
To post to this group, send email to django-users@googlegroups.com.
Visit this group at https://groups.google.com/group/django-users.
To view this discussion on the web visit 
https://groups.google.com/d/msgid/django-users/CA%2Be%2BciUAVuRFAc9Z6PvuNSh5p4jh_ZrPbvyPjWQfW2ccMPnTOg%40mail.gmail.com.
For more options, visit https://groups.google.com/d/optout.

Reply via email to