Yathartha Joshi
Yathartha Joshi

Reputation: 776

Displaying ForeignKey attributes in DRF

When I run the api, instead of getting category name and subcategory name, I get their id,

[
    {
        "id": 1,
        "name": "StrawBerry",
        "category": 1,
        "subcategory": 1
    }
]

I actually want something like this:

[
    {
        "id": 1,
        "name": "StrawBerry",
        "category": "Fruits",
        "subcategory": "Berries"
    }
]

Note: I already have category and subcategory. I just want to know how to access them.

models.py

from django.db import models

class Category(models.Model):
    category = models.CharField(max_length=200)
    parent = models.ForeignKey('self', blank=True, null=True, related_name='children')

    class Meta:
        unique_together = ('parent' , 'category')

    def __str__(self):
        return self.category

class SubCategory(models.Model):
    subcategory = models.CharField(max_length=200)
    category = models.ForeignKey('Category', null=True, blank=True)
    parent = models.ForeignKey('self', blank=True, null=True, related_name='subchilren')

    class Meta:
        unique_together = ('parent' , 'subcategory')

    def __str__(self):
        return self.subcategory

class Product(models.Model):
    name = models.CharField(max_length=200)
    category = models.ForeignKey('Category', null=True, blank=True)
    subcategory = models.ForeignKey('SubCategory', null=True, blank=True)

    def __str__(self):
        return self.name

serializers.py

class GetProductSerializer(serializers.ModelSerializer):
    class Meta:
        model = Product
        fields = ('id', 'name', 'category', 'subcategory')

views.py

class GetProductViewSet(viewsets.ModelViewSet):
    serializer_class = GetProductSerializer
    queryset = Product.objects.all()

Upvotes: 2

Views: 682

Answers (1)

souldeux
souldeux

Reputation: 3755

One solution would be to define the category and subcategory fields of your GetProductSerializer as StringRelatedFields:

StringRelatedField may be used to represent the target of the relationship using its unicode method.

http://www.django-rest-framework.org/api-guide/relations/#stringrelatedfield

Or, similarly, as SlugRelatedFields:

SlugRelatedField may be used to represent the target of the relationship using a field on the target.

http://www.django-rest-framework.org/api-guide/relations/#slugrelatedfield

Upvotes: 1

Related Questions