Nikhil Garg
Nikhil Garg

Reputation: 4014

Serializing/deserializing a foreign key in django rest framework

I'm using the Django rest framework to create an API. Say I have the following models:

class Category(models.Model):
    name = models.CharField(max_length=100)

    def __unicode__(self):
        return self.name


class Item(models.Model):
    name = models.CharField(max_length=100)
    category = models.ForeignKey(Category, related_name='items')

    def __unicode__(self):
        return self.name

I want to write a serializer for Item such that it returns "category_name" during serialization (i.e. read) but then also takes "category_name" back and converts it into category during deserialization (i.e. write) [you can assume that category_name is unique in its table]

I was able to find this link which solves the problem for reads but doesn't work for writes.

class ItemSerializer(serializers.ModelSerializer):
    category_name = serializers.CharField(source='category.name')

    class Meta:
        model = Item
        fields = ('id', 'name', 'category_name')

Is there a way to modify it such that it can be used to populate new items via an API?

Upvotes: 2

Views: 604

Answers (1)

Guillaume
Guillaume

Reputation: 2006

SlugRelatedField is what you're looking for. This is both read and write.

class ItemSerializer(serializers.ModelSerializer):
    category = serializers.SlugRelatedField(
        slug_field='name',
        queryset=Category.objects.all()
     )

    class Meta:
        model = Item
        fields = ('id', 'name', 'category')

Precision: you need to make your category.name unique=True in your models.py.

Upvotes: 4

Related Questions