0

I'm currently working on DRF.

models.py

class Post(models.Model):
    id = models.IntegerField()
    content = models.CharField()
    category = models.CharField()
    created = models.CharField()

Below, the Response I want to get

[
    {
      "id": "1",
      "content": "a",
      "category": "post",
      "created": "2020-01-23"
    },
    {
      "id": "3",
      "content": "b"
    },
]

How can I get the response like above just using ONE model.

2
  • convert data from model to dictionary or json Commented Jan 23, 2020 at 12:57
  • 1
    Use DRF Serializers Commented Jan 23, 2020 at 12:58

2 Answers 2

1

So basically you need to take a look first at https://www.django-rest-framework.org/api-guide/serializers/#modelserializer.

Hope this example can help you:

view.py

class PostListView(BaseApiView):
    serializer_class = PostListSerializer

    def get(self, request, *args, **kwargs):
        posts = list(Post.objects.all())
        res = PostListSerializer(posts, many=True)
        return Response(res.data)

serializers.py

class PostListSerializer(serializers.ModelSerializer):
    def to_representation(self, instance):
        data = super(PostListSerializer, self).to_representation(instance)
        if not data.get('category'):
            data.pop('category', None)
            data.pop('created', None)
        return data

    class Meta:
        model = Post
        fields = '__all__'
Sign up to request clarification or add additional context in comments.

Comments

0

You could use a dynamic serializer and do something like this:

serializers.py

class PostSerializer(DynamicFieldsModelSerializer):
    class Meta:
        model = Post
        fields = ['id', 'content', 'category', 'created']

views.py

from rest_framework import status
from rest_framework.response import Response
from rest_framework.views import APIView
from .serializers import PostSerializer


class PostListView(APIView):
    def get(self, request, format=None):
        post1 = Post.objects.get(id=1)
        post3 = Post.objects.get(id=3)
        post1_serializer = PostSerializer(post1)  # all fields
        post3_serializer = PostSerializer(post3, fields=['id', 'content'])
        data = [post1_serializer.data, post3_serializer.data]
        return Response(data, status=status.HTTP_200_OK)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.