Discussion:
Browsable API and ForeignKey
r***@gmail.com
2018-10-09 13:39:02 UTC
Permalink
How do I get DRF to render a select field for selecting a related model on
a foreignkey field? Cannot find this covered in the docs and most of my
models have a related model in the form of a user or group or category and
need a select field in order to be used. Is there some extra parameter to
pass?

An example serializer is below. The Author is not required as it will be
set to the logged in user on create, but the writing_form and category are
required for creation, so the API Create and Update forms are not usable
for testing the API:

class WritingSerializer(serializers.ModelSerializer):
"""
Main serializers for the writings module
"""
author = MemberListSerializer(many=False, read_only=True)
writing_form = WritingFormSerializer(many=False, read_only=True)
category = CategorySerializer(many=False, read_only=True)
comments = CommentSerializer(many=True, read_only=True)

class Meta:
model = Writing
fields = (
'id',
'slug',
'url',
'title',
'description',
'created',
'edited',
'writing_form',
'category',
'author',
'body',
'comments'
)
lookup_field = 'slug'
extra_kwargs = {
'url': {'lookup_field': 'slug'}
}
--
You received this message because you are subscribed to the Google Groups "Django REST framework" group.
To unsubscribe from this group and stop receiving emails from it, send an email to django-rest-framework+***@googlegroups.com.
For more options, visit https://groups.google.com/d/optout.
r***@gmail.com
2018-10-09 14:01:11 UTC
Permalink
Oh derp, figured this out. Need the HyperlinkedRelatedField and
writable=True
Post by r***@gmail.com
How do I get DRF to render a select field for selecting a related model on
a foreignkey field? Cannot find this covered in the docs and most of my
models have a related model in the form of a user or group or category and
need a select field in order to be used. Is there some extra parameter to
pass?
An example serializer is below. The Author is not required as it will be
set to the logged in user on create, but the writing_form and category are
required for creation, so the API Create and Update forms are not usable
"""
Main serializers for the writings module
"""
author = MemberListSerializer(many=False, read_only=True)
writing_form = WritingFormSerializer(many=False, read_only=True)
category = CategorySerializer(many=False, read_only=True)
comments = CommentSerializer(many=True, read_only=True)
model = Writing
fields = (
'id',
'slug',
'url',
'title',
'description',
'created',
'edited',
'writing_form',
'category',
'author',
'body',
'comments'
)
lookup_field = 'slug'
extra_kwargs = {
'url': {'lookup_field': 'slug'}
}
--
You received this message because you are subscribed to the Google Groups "Django REST framework" group.
To unsubscribe from this group and stop receiving emails from it, send an email to django-rest-framework+***@googlegroups.com.
For more options, visit https://groups.google.com/d/optout.
Loading...