Answer the question
In order to leave comments, you need to log in
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)
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__'
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})
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)
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 questionAsk a Question
731 491 924 answers to any question