-
-
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
#3255
Add a method to return the string value used in choices
of a RelatedField
#3255
Conversation
Returns the text representation of the instance. Subclasses can override this method to provide a different display value used for populating the `choices` property.
class TrackPrimaryKeyRelatedField(serializers.PrimaryKeyRelatedField): | ||
def display_value(self, instance): | ||
return 'Track: %s' % (instance.title) | ||
|
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Okay, great! I think it'd be worth finally noting that...
"These string representations will be used in select HTML inputs in the browsable API"
or similar. Just to make it absolutely clear when and why you would choose to override this method.
I've update the docs with your suggestion. Just to note, GitHub's source diff for that Markdown file is completely wrong for me for both commits, however viewing the rich diff displays the changes correctly. |
I think drop duplicated six.text_type on L151, right? |
Since we already do that in the method. |
Possibly. It depends how strictly you define the API. Is it Could there be a use case where someone is iterating the field's queryset in some of their own logic and calling the |
I'd leave it down to the user to deal with. It'll be used in template code so it'll get coerced in any case. |
Ah apologies, I originally read that wrong, I was looking at L161. Yes to removing it from L151. |
The `display_value` method returns a text type.
Lovely stuff! |
Add a method to return the string value used in `choices` of a `RelatedField`
Issue #3254