Aromal Sasidharan
Aromal Sasidharan

Reputation: 678

django rest framework Serialization of foreign key

I just started to learn django rest framework and the following are files of my Topic app

======models.py=====

from django.contrib.auth.models import User
class Topic(models.Model):
    title = models.CharField(max_length=100,verbose_name="Topic Title")
    description = models.CharField(max_length=500, verbose_name="Topic Description")
    user = models.ForeignKey(to=User,related_name="user_topics")

=====serializers.py=====

class TopicSerializer(ModelSerializer):
    class Meta:
        model = Topic
        fields = "__all__"

=====views.py=====

class TopicViewSet(ModelViewSet):
    queryset = Topic.objects.all()
    serializer_class = TopicSerializer

I'am able to create a "Topic" data using httpie as follows

http POST http://127.0.0.1:8989/api/v1/topics/ description="Learn Python" title="Python" user=1

NOW my need is that the topic detail should have the "user" key expanded for the User - (While maintaining the same "user" key to PASS user id to create a topic) ie.,

making a GET request to the detail should return the following

http GET http://127.0.0.1:8989/api/v1/topics/1/
=====
HTTP/1.0 200 OK

{
    "description": "Learn Python", 
    "id": 1, 
    "title": "Python", 
    "user": { name:"blah blah"
        ...
        ...
     }      
}

AND

Making a post with user id in "user" key should create the "Topic" and should return the response with user expanded in "user" key ie.,

http POST http://127.0.0.1:8989/api/v1/topics/ description="Learn Python" title="Python" user=1
HTTP/1.0 201 Created
....

{
    "description": "Learn Python", 
    "id": 1, 
    "title": "Python", 
    "user": { name:"blah blah", ...}
}

What changes do i need to make, so that i will be able to use the SAME "user" key? for 3 following purpose

  1. to make a POST with "user id" to create a Topic // user:1
  2. The POST response returned while creating a Topic should have the user expanded in user key //user : { name:"blah blah", ...}
  3. Also, to GET the detail expanded // user : { name:"blah blah", ...}

or please suggest an better way of doing this.

Upvotes: 2

Views: 2565

Answers (2)

Rahul Kant
Rahul Kant

Reputation: 157

In ====serializers.py======= you can make these changes

from rest_framework import serializers  
from models import Topic

class TopicSerializer(ModelSerializer):
   title = serializers.CharField(max_length=100,verbose_name="Topic Title")
   description = serializers.CharField(max_length=500, verbose_name="Topic Description")
   user = serializers.PrimaryKeyRelatedField(queryset = User.objects.all(),related_name="user_topics")
   class Meta:
      model = Topic
      fields = "__all__"

  def create(self, validated_data):
      return Topic.objects.create(**validated_data)

  def update(self, instance, validated_data):
      instance.title = validated_data.get('title', instance. title)
      instance.description = validated_data.get('description', instance. description)
      instance.user = validated_data.get('user', instance. user)
      instance.save()
      return instance

 def delete(self, instance):
      instance.delete() 
      return True

Upvotes: 0

v1k45
v1k45

Reputation: 8250

You can select a different version of PostSerializer depending of the type of request to receive.

Change your ModelViewSet's get_serializer_class method to do so:

class PostViewSet(ModelViewSet):
    queryset = Post.objects.all()

    def get_serializer_class(self):
        if self.action == 'create':
            return PostSerializerWithUserID
        else:
            return PostSerializerWithNestedUser

Upvotes: 1

Related Questions