-
-
Notifications
You must be signed in to change notification settings - Fork 6.9k
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Add a method to return the string value used in choices
of a RelatedField
#3254
Comments
Thanks James - appreciate the in-depth issue. I think something like A pull request here would be great. I guess that the best place to include this in the docs would be somewhere in the "further notes" for serializer relations. - http://www.django-rest-framework.org/api-guide/relations/#further-notes |
I agree the name I'll look in to a pull request for this. |
Wünderbar. 😄 |
Add a method to return the string value used in `choices` of a `RelatedField`
Great work :) |
The
choices
property of theRelatedField
class returns anOrderedDict
with the values set to the__str__
(__unicode__
on Python 2) representation of the models in the queryset. I propose adding a method that subclasses can override to provide the value used in the dictionary (namedlabel_from_instance
in the following example).An example. An address model has a foreign key relationship with a country model.
A model serializer is declared using the address model.
In the template a HTML select control is rendered for the user (customer) to choose a country for their address. This is achieved by using the country field's
choices
property. (Jinja2 template syntax)The rendered HTML is.
And the user (customer) sees this in the browser.
The
choices
values are the__str__
representation of the model. Whilst this works for most cases there can be times when a different value displayed to the user is desired.Continuing on the example. A different user (staff) of the system may also be editing instances of the same country model but would benefit from additional information than that of other users (customers), in this case the
iso_code
.With the use of a method that subclasses can implement to provide the values for the choices this could be achieved. The serializer would be written as so.
The same template syntax could be used and the rendered HTML would now be.
And the user (staff) sees this in the browser.
Related discussion group.
The text was updated successfully, but these errors were encountered: