John
John

Reputation: 6065

How to show object details in Django Rest Framework browseable API?

This image should explain my question: enter image description here

I have a model that is made up of two foreign keys, as follows:

class StaffRole(models.Model):
staff = models.ForeignKey(Staff, related_name='roles')
role = models.ForeignKey(Role, related_name='staff')

class Meta:
    unique_together = ('staff', 'role')

def __str__(self):
    return '%s / %s' % (self.staff, self.role)

It has a straightforward serializer, as follows:

class StaffRoleSerializer(serializers.HyperlinkedModelSerializer):
role = serializers.SlugRelatedField(
    queryset=Role.objects.all(),
    slug_field='slug'
)
staff = serializers.SlugRelatedField(
    queryset=Staff.objects.all(),
    slug_field='slug'
)

class Meta:
    model = StaffRole

Using the Django Rest Framework SlugRelatedField, I am hoping that the combo boxes in the browseable API will show the slugs of the related models, but instead the combo boxes are populated with the words "Role Object" and "Staff Object", so the user cant tell which role or which staff they are selecting in the combo box.

How do I remedy this?

To avoid complexity I'm trying to use the default DRF serializers, such as SlugRelatedField, rather than write my own nested serializers. Everything works except the combo boxes in the browseable API.

Thanks in advance

John

PS It's not my intention to make the browseable API the user interface to this app. But I do want it to work, and I find it invaluable in the development cycle.

Upvotes: 1

Views: 1739

Answers (1)

Joey Wilhelm
Joey Wilhelm

Reputation: 5819

To change those representations, you need to set a __str__ method on the models. And, if you're using Python 2, you should also then decorate the model class with the python_2_unicode_compatible decorator. For example:

from django.db import models
from django.utils.encoding import python_2_unicode_compatible


@python_2_unicode_compatible
class Role(models.Model):
    name = models.CharField(...)

    def __str__(self):
        return self.name

The decorator will essentially clone the __str__ method and make it also available as __unicode__, as Python 2 would expect.

Upvotes: 3

Related Questions