M
M
Mike2018-08-03 14:45:47
Django
Mike, 2018-08-03 14:45:47

How to display all posts of a specific category?

I am using DRF. There are two simple models "Post", "Category". I don't know how to display all posts that belong to a particular category.
models.py

class Category(models.Model):

    name = models.CharField(max_length=250)

class Post(models.Model):

    title = models.CharField(max_length=250)
    body = models.TextField()
    created = models.DateTimeField(auto_now_add=True)
    updated = models.DateTimeField(auto_now=True)
    category = models.ForeignKey(Category, related_name='entries', on_delete=models.CASCADE)

serializers.py
from . models import Post, Category
from rest_framework import serializers

class CategorySerializer(serializers.ModelSerializer):

    class Meta:

        model = Category 
        fields = '__all__'

class PostSerializer(serializers.ModelSerializer):

    class Meta:

        model = Post
        fields = '__all__'

views.py
from rest_framework.response import Response
from django.shortcuts import render
from rest_framework.generics import ListAPIView, RetrieveAPIView
from . models import Post, Category
from . serializers import PostSerializer, CategorySerializer
from rest_framework.views import APIView

class GetCategory(APIView):

    def get(self, request, id):
        cat = Category.objects.select_related().get(id=id) 
        p = Post.objects.filter(category_id=id).all()
        cat_serializer = CategorySerializer(cat, many=True)
        p_serializer = PostSerializer(p, many=True)
        return Response({'cat': cat_serializer.data, 'p': p_serializer.data})

In views.py "GetCategory" I try to get all the posts of a particular category, but it's a fiasco. That is, I go to localhost://8000/api/category/ 2
this is my url for "GetCategory" path('api/category//', views.GetCategory.as_view()),
PS: Solution. Change class GetCategory
views
class GetCategory(APIView):

    def get(self, request, id):
        p = Post.objects.filter(category_id=id).all()
        serializer = PostSerializer(p, many=True)
        return Response(serializer.data)

and in urls.py replace "pk" with "id"
path('api/category/<int:id>/', views.GetCategory.as_view()),

Answer the question

In order to leave comments, you need to log in

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question