DRF Get likes and dislikes grouped by day - django

I have a models named Post and Like. How can i get json with ount of likes and dislikes grouped by date (date field in Like model)?
Here is my models.py
class Post(models.Model):
"""Post model"""
author = models.ForeignKey(User, on_delete=models.CASCADE)
title = models.CharField(max_length=255)
body = models.TextField()
created_at = models.DateTimeField(auto_now_add=True)
def __str__(self):
return self.title
class Like(models.Model):
"""Like model"""
LIKE = (
('like', 'like'),
('dislike', 'dislike')
)
user = models.ForeignKey(User, on_delete=models.CASCADE)
post = models.ForeignKey(Post, on_delete=models.CASCADE, related_name='likes')
like = models.CharField(max_length=255, choices=LIKE)
date = models.DateField(auto_now=True)
Here is my serializers.py:
class AnaliticsSerializer(serializers.ModelSerializer):
"""Like analitic"""
class Meta:
model = Like
fields = '__all__'
Here is my vievs.py:
class AnaliticView(ListAPIView):
queryset = Like.objects.all()
serializer_class = AnaliticsSerializer
filter_backends = [DjangoFilterBackend]
filter_fields = ['date']
result what i want
[
{
"date": "2020-11-14",
"total_likes": 25,
"total_dislikes": 17
},
{
"date": "2020-11-15",
"total_likes": 38,
"total_dislikes": 8
},
{
"date": "2020-11-18",
"total_likes": 11,
"total_dislikes": 0
}

Here's a working example of one basic approach to this. It should give you the idea.
The analytics code shouldn't really be in the view. Also, some of the grouping and counting might be offloaded to the database, using advanced ORM querying like this.
views.py
from collections import Counter
from datetime import datetime, timedelta
from itertools import groupby
from django_filters import rest_framework as filters
from rest_framework.generics import GenericAPIView
from rest_framework.response import Response
from likes.filters import DateRangeFilterSet
from likes.models import Like
class AnaliticView(GenericAPIView):
queryset = Like.objects.all()
filter_backends = (filters.DjangoFilterBackend,)
filterset_class = DateRangeFilterSet
def get(self, request, format=None):
queryset = self.get_queryset()
filtered_queryset = self.filter_queryset(queryset)
# Queryset needs to be ordered by date for groupby to work correctly
ordered_queryset = filtered_queryset.order_by('date')
likes_by_date = groupby(ordered_queryset,
lambda like: like.date.strftime("%Y-%m-%d"))
analytics = []
for date, likes in likes_by_date:
count = Counter(like.like for like in likes)
analytics.append(
{
'date': date,
'total_likes': count['like'],
'total_dislikes': count['dislike'],
}
)
return Response(analytics)
Like I said in the comments, it would be possible to create a lightweight class with attributes for date and the two totals, and pass a list of instances of that to a serializer to get the response data. In my opinion, that's overkill as you can just build a dictionary that is easily serialised into JSON.
Update:
I've switched to a GenericAPIView, which is a superclass of ListAPIView, because it supports filter backends. I have added a FilterSet that filters by date_from and date_to:
filters.py
from django_filters import rest_framework as filters
from likes import models
class DateRangeFilterSet(filters.FilterSet):
date_from = filters.DateFilter(field_name='date', lookup_expr='gte')
date_to = filters.DateFilter(field_name='date', lookup_expr='lte')
class Meta:
model = models.Like
fields = ('date_from', 'date_to')

Related

Django Rest API issue with retrieving correct information from urls. It is a Grandparent - Parent - Child relationship. How do I correctly map them?

I have been stuck on this problem for about 9 hours and am having trouble understanding the Grandparent - Parent - Child relationship with a One to Many Relationship(foreign key) in Django.
I am currently creating an E-Commerce website and am trying to display the information in 4 different ways to fetch from my React frontend.
I have 3 models setup:
Category
Subcategory (Foreign key to Category)
Products (Foreign Key to Subcategory)
This is the result I am attempting to create in my urls/views/serializer files:
For some reason I can successfully retrieve at a granular level for a single product but as soon as I start going up nested models I am running into the following errors:
Desired Result
I have api/ included in the core urls folder already.
I want JSON to display the information like this.
# URLSearch api/Category/
# Category -
# |
# Subcategory 1 -
# |
# Product 1
# Product 2
# Subcategory 2 -
# |
# Product 1
# Proudct 2
I also want JSON to display the information like this.
# URLSearch api/Category/Subcategory/
# Category -
# |
# Subcategory -
# |
# Product 1
# Product 2
Errors
Error 1:
Got AttributeError when attempting to get a value for field slug on serializer SubcategoryListSerializer.
The serializer field might be named incorrectly and not match any attribute or key on the QuerySet instance.
Original exception text was: 'QuerySet' object has no attribute 'slug'.
Error 2:
Returns Wrong Object piggies back off issue above - I deleted my code to clean it up file as I have been attempting this for 10+ hours so there is currently a place holder route there.
Urls.py
from django.contrib import admin
from django.urls import path, include
from rest_framework import routers
from api import views
urlpatterns = [
path('search/<slug:category_slug>/<slug:subcategory_slug>/',
views.SubcategoryListView.as_view()), #Error 1
path('search/<slug:category_slug>/', views.AllProductsListView.as_view()), # Error 2
path('all-products/', views.AllProductsListView.as_view()), # Good
path('search/<slug:category_slug>/<slug:subcategory_slug>/<slug:product_slug>',
views.ProductDetail.as_view()), # WORKS
# path('all-products/', views.AllProductsListView.as_view())
]
Models.py
from django.db import models
import uuid
# Create your models here.
class Category(models.Model):
slug = models.SlugField(
primary_key=True, max_length=50, null=False, unique=True)
class Meta:
ordering = ('slug',)
def __str__(self):
return self.slug
def get_absolute_url(self):
return f'/{self.slug}/'
class Subcategory(models.Model):
slug = models.SlugField(
primary_key=True, max_length=50, null=False, unique=True)
category = models.ForeignKey(Category, on_delete=models.CASCADE)
class Meta:
ordering = ('category',)
def __str__(self):
return self.slug
def get_absolute_url(self):
return f'/{self.category.slug}/{self.slug}/'
class Products(models.Model):
subcategory = models.ForeignKey(Subcategory, on_delete=models.CASCADE)
newAdd = models.BooleanField(default=False)
name = models.CharField(max_length=200)
slug = models.SlugField(
primary_key=True, max_length=50, null=False, unique=True)
imageOne = models.CharField(max_length=100)
imageTwo = models.CharField(max_length=100, null=True)
imageThree = models.CharField(max_length=100, null=True)
colors = models.CharField(max_length=300) # This is going to be a list
price = models.FloatField()
dateCreated = models.DateField(auto_now_add=True)
class Meta:
ordering = ('-dateCreated',)
def __str__(self):
return self.slug
def get_absolute_url(self):
return f'/{self.subcategory.category.slug}/{self.subcategory.slug}/{self.slug}'
Views
from django.shortcuts import render
from .serializers import AllProductsSerializer, CategorySerializer, SubcategoryListSerializer, ProductsSerializer, SubcategorySerializer
from rest_framework import viewsets, generics, views, response
from products.models import Products, Subcategory, Category
# Create your views here.
class ProductDetail(views.APIView):
def get_object(self, category_slug, subcategory_slug, product_slug):
obj = Products.objects.filter(subcategory__category__slug=category_slug).filter(
subcategory=subcategory_slug).get(slug=product_slug)
return obj
def get(self, request, category_slug, subcategory_slug, product_slug):
print(request)
product = self.get_object(
category_slug, subcategory_slug, product_slug)
serializer = ProductsSerializer(product)
return response.Response(serializer.data)
class SubcategoryListView(views.APIView):
def get_object(self, category_slug, subcategory_slug):
obj = Products.objects.filter(
subcategory__category__slug=category_slug)
return obj
def get(self, request, category_slug, subcategory_slug):
products = self.get_object(category_slug, subcategory_slug)
serializer = SubcategoryListSerializer(products)
return response.Response(serializer.data)
class AllProductsListView(generics.ListAPIView):
serializer_class = AllProductsSerializer
queryset = Products.objects.all()
class CategoryListView(generics.ListCreateAPIView):
queryset = Products.objects.all()
serializer_class = Category
Serializers
from rest_framework import serializers
from products.models import Products, Category, Subcategory
class ProductsSerializer(serializers.ModelSerializer):
class Meta:
model = Products
fields = (
'newAdd',
'name',
'slug',
'imageOne',
'price',
'dateCreated',
'get_absolute_url',
)
class SubcategoryListSerializer(serializers.ModelSerializer):
class Meta:
model = Products
fields = ('__all__')
class SubcategorySerializer(serializers.ModelSerializer):
items = SubcategoryListSerializer(many=True, read_only=True)
class Meta:
model = Subcategory
fields = (
'slug',
'items'
'get_absolute_url',
)
class AllProductsSerializer(serializers.ModelSerializer):
class Meta:
model = Category
fields = ('__all__')
class CategorySerializer(serializers.ModelSerializer):
class Meta:
model = Products
fields = ('__all__')

NOT NULL constraint failed: shipping_ship.user_id Django

So I'm working on a shipping website with the django rest framework. The website brings two to four people together so they can easily ship their goods together at the same time. But I'm facing a major stumbling block on the views where user book a shipping the code is below.
models.py
from django.db import models
from django.contrib import get_user_model
User = get_user_model()
class Container(models.Model):
container_type = models.Charfield(max_length = 30, blank=False, null = False)
max_users = models.IntegerField()
price = models.DecimalField(max_digits=10, decimal_places =2, default=0, blank=True, null=True)
users = models.ManyToManyField(User)
class Ship(models.Model):
container = models.ForeignKey(Container, related_name='cont', on_delete=models.CASCADE)
user = models.ForeignKey(User, related_name='shipper', on_delete=models.CASCADE)
location = (
('France', 'France'),
)
from_location = models.CharField(max_length=30, choices=location, blank=False, null=False)
to_location = (
('Lagos', 'Lagos'),
('Abuja', 'Abuja'),
('Abeokuta', 'Abeokuta'),
('Osun', 'Osun'),
)
to_location = models.CharField(max_length=30, choices=to_location, blank=False, null=False)
date_leaving = models.DateField(auto_now=False)
price = models.DecimalField(max_digits=10, decimal_places=2, default=0, blank=True, null=True)
def __str__(self):
return self.user
then my serializer.py file
from rest_framework import serializers
from .models import Container, Ship
class ContainerSerializer(serializers.ModelSerializer):
class Meta:
model = Container
fields = '__all__'
class MiniContainerSerializer(serializers.ModelSerializer):
class Meta:
model = Container
fields =['container_type', 'price']
class ShipSerializer(serializers.ModelSerializer):
class Meta:
model = Ship
fields = '__all__'
read_only_fields = ('user', 'price')
class MiniShipSerializer(serializers.ModelSerializer):
class Meta:
model = Ship
fields = ['container', 'from_location', 'to_location']
and now my views.py file which I have issues with
from django.shortcuts import render
from django.shortcuts import get_object_or_404
from rest_framework.generics import ListCreateAPIView, CreateAPIView, ListAPIView, RetrieveUpdateDestroyAPIView, RetrieveAPIView
from .serializers import ContainerSerializer, MiniContainerSerializer, ShipSerializer, MiniShipSerializer
from rest_framework import permissions, status
from rest_framework.response import Response
from .models import Container, Ship
class ShipAPI(ListCreateAPIView):
serializer_class = ShipSerializer
def get_queryset(self):
user = self.request.user
queryset = Ship.objects.filter(user=user)
return queryset
def Book_shipping(self, request, *args, **kwargs):
user = request.user
container = get_object_or_404(Container, pk=request.data['container'])
if container.users.count() >= container.max_users:
return Response('container already full')# here i'm trying to set limits so the users joining each container won't surpass the max users.
cont = container(users=user)
cont.save()
from_location = (request.data['from_location'])
to_location = (request.data['to_location'])
date_leaving = int(request.data['date_leaving'])
price = container.price / container.max_users
cart = Ship(container=container, user=user, from_location=from_location, to_location=to_location, date_leaving=date_leaving, price=price)
cart.save()
serializer = ShipSerializer(cart)
data ={'message': 'shipping successfully created',
'data':serializer.data}
return Response(data=data, status=status.HTTP_201_CREATED)
and then after testing the endpoint it returns this error:
IntegrityError at /Shipping/Ship/
NOT NULL constraint failed: shipping_ship.user_id
I've tried debugging and looking at it over and over again can someone please help me? Thanks in advance. And yes I've tried deleting migrations and the database.
As your Container model have a ManyToMany relationship with the User model.
So it may not work like cont = container(users=user)
For me it worked like this:
cont = container.users.add(user)
cont.save()

Joining two tables and search/filter within serialized data with django-rest-framework

I am joining two tables than I would like to do keyword searching. I need to create a single SQL and add a WHERE with argument(s). I am using django-rest-framework.
models.py
from django.db import models
class Paper(models.Model):
title = models.TextField()
paper_lan = models.CharField(max_length=2)
nb_authors = models.SmallIntegerField()
class Meta:
managed = False
def __str__(self):
return str(self.title)
class Abstract(models.Model):
paper = models.OneToOneField(Paper,
related_name='abstracts',
on_delete=models.CASCADE,
primary_key=True)
abstract = models.TextField()
class Meta:
managed = False
def __str__(self):
return str(self.abstract)
serializers.py
from rest_framework import serializers
from .models import Paper, Abstract
class PaperAbstractSerializer(serializers.ModelSerializer):
class Meta:
model = Paper
#fields = '__all__'
fields = ['title', 'paper_lan', 'nb_authors', 'abstracts']
depth = 1
class PaperSerializer(serializers.ModelSerializer):
class Meta:
model = Paper
fields = ('title', 'paper_lan', 'nb_authors')
class AbstractSerializer(serializers.ModelSerializer):
class Meta:
model = Abstract
fields = ['abstract']
filters.py
from django.db.models import Q
from django_filters.rest_framework import CharFilter, FilterSet
from .models import Paper, Abstract
class PaperAbstractFilterSet(FilterSet):
query = CharFilter(method='qfilter')
class Meta:
model = Paper
fields = ['query']
def qfilter(self, queryset, name, value):
squery = Q(abstracts__icontains=value)
return queryset.filter(squery)
class PaperFilterSet(FilterSet):
query = CharFilter(method='qfilter')
class Meta:
model = Paper
fields = ['query']
def qfilter(self, queryset, name, value):
squery = Q(title__icontains=value)
return queryset.filter(squery)
class AbstractFilterSet(FilterSet):
query = CharFilter(method='qfilter')
class Meta:
model = Abstract
fields = ['query']
def qfilter(self, queryset, name, value):
squery = Q(abstract__icontains=value)
return queryset.filter(squery)
views.py
from rest_framework.generics import ListAPIView
from .models import Paper, Abstract
from .serializers import PaperAbstractSerializer, PaperSerializer, AbstractSerializer
from .filters import PaperAbstractFilterSet, PaperFilterSet, AbstractFilterSet
class PaperAbstractView(ListAPIView):
queryset = Paper.objects.all()
serializer_class = PaperAbstractSerializer
filterset_class = PaperAbstractFilterSet
class PaperView(ListAPIView):
queryset = Paper.objects.all()
serializer_class = PaperSerializer
filterset_class = PaperFilterSet
class AbstractView(ListAPIView):
queryset = Abstract.objects.all()
serializer_class = AbstractSerializer
filterset_class = AbstractFilterSet
urls.py
from django.urls import path
from .views import PaperAbstractView, PaperView, AbstractView
urlpatterns = [
path('paperabs/', PaperAbstractView.as_view()),
path('paper/', PaperView.as_view()),
path('abstract/', AbstractView.as_view()),
]
When I run the followings, searching is made on a single table, everything is fine. There is only a single SQL which is produced.
curl "http://localhost:8003/api/v1/appln/abstract/?query=<keyword_searching>"
curl "http://localhost:8003/api/v1/appln/paper/?query=<keyword_searching>"
But, when I run the following request, I cannot make any keyword search. If I comment the filterset_class = PaperAbstractFilterSet ligne in PaperAbstractView, there is one SQL and then relatedly there are n other SQL produced for the second table.
curl "http://localhost:8003/api/v1/appln/paperabs/?query=<keyword_searching>"
How can I create a single SQL with the complementary WHERE to conduct any search on title and/or abstract?
To answer my own question; to join two tables in a single SQL I use select_related and correct the serializers.py by adding the LEFT JOINed table's serializer, AbstractSerializer into PaperAbstractSerializer.
# serializers.py
class PaperAbstractSerializer(serializers.ModelSerializer):
abstracts = AbstractSerializer(read_only=True)
class Meta:
model = Paper
fields = ['title', 'paper_lan', 'nb_authors', 'abstracts']
# views.py
class PaperAbstractView(ListAPIView):
queryset = Paper.objects.select_related('abstracts').all()
serializer_class = PaperAbstractSerializer
filterset_class = PaperAbstractFilterSet

Nested serializers and data representation

Working on a django project I am a bit stuck on data representation through APIs. In fact when designing models the data model is quite stratighforward : I have a one to many relationship A--> B
therefore I have added a FK to object B.
Object B has a boolean attribute "active".
I would like to make an API call to list all A objects having at least one assoicated object B with active = true.
The api could be like this :
/api/objectA/?ObjectB.active=True
Here is my code :
Models :
from django.contrib.postgres.fields import ArrayField
from django.core.exceptions import ValidationError
from django.db import models
from django.db.models.signals import pre_save
from django.dispatch import receiver
class Startup(models.Model):
header = models.CharField("Header", max_length=255)
title = models.CharField("Title", max_length=255)
description = models.CharField("description", max_length=255)
# TODO Change this to options instead of array
tags = ArrayField(models.CharField(max_length=10, blank=True), size=5)
# TODO Images to be stored in aws only url will be in DB
card_image = models.ImageField(upload_to='media/images/cards')
logo_image = models.ImageField(upload_to='media/images/logos')
main_img = models.ImageField(upload_to='media/images/main', null=True)
createdAt = models.DateTimeField("Created At", auto_now_add=True)
def __str__(self):
return self.title
class Investment(models.Model):
# TODO change the name of Investment to fund round in back and front
# TODO all price to be checked for max digits and decimal places
startup = models.ForeignKey(Startup, related_name='startup_investments', on_delete=models.CASCADE, default="1")
# Use the related_name as a serializer bale for investments inside startup serializer
Investment_title = models.CharField("Investment_title", max_length=255, default="Missing Title")
collected_amount = models.DecimalField(max_digits=12, decimal_places=2)
goal_percentage = models.IntegerField(default=0)
number_of_investors = models.IntegerField(default=0)
days_left = models.IntegerField()
active = models.BooleanField(default=False)
# TODO Need to update this to prevent linking to a non existing startup
createdAt = models.DateTimeField("Created At", auto_now_add=True)
def clean(self):
"""Validate that the startup does not have already an active Investment """
if self.active:
qs = Investment.objects.filter(active=True).filter(startup=self.startup)
if self.pk is not None:
qs = qs.exclude(pk=self.pk)
if qs:
raise ValidationError(message="An active investment already exists for this startup")
def __str__(self):
return self.Investment_title
Serializers :
from rest_framework import serializers
from .models import Startup, Investment
class InvestmentSerializer(serializers.ModelSerializer):
class Meta:
model = Investment
fields = ('id', 'Investment_title', 'collected_amount', 'goal_percentage', 'number_of_investors',
'days_left', 'active')
class StartupSerializer(serializers.ModelSerializer):
startup_investments = InvestmentSerializer(many=True, read_only=True)
class Meta:
model = Startup
fields = ('id', 'header', 'title', 'description', 'tags', 'card_image',
'logo_image', 'main_img', 'startup_investments')
Views :
from django_filters import rest_framework as filters
from rest_framework.viewsets import ModelViewSet
from rest_framework_extensions.mixins import NestedViewSetMixin
from .serializers import *
class StartUpViewSet(NestedViewSetMixin, ModelViewSet):
"""
Class that provides List, Retrieve, Create, Update, Partial Update and Destroy actions for startups.
It also include a filter by startup status
"""
model = Startup
queryset = Startup.objects.all()
serializer_class = StartupSerializer
class InvestmentViewSet(NestedViewSetMixin, ModelViewSet):
"""
Class that provides List, Retrieve, Create, Update, Partial Update and Destroy actions for Investments.
It also include a active and investment title
"""
model = Investment
serializer_class = InvestmentSerializer
queryset = Investment.objects.all()
filter_backends = (filters.DjangoFilterBackend,)
filterset_fields = ('active', 'Investment_title')
routers :
router = ExtendedSimpleRouter()
(
router.register(r'api/investments', views.InvestmentViewSet, basename='investment'),
router.register(r'api/startups', views.StartUpViewSet, basename='startup')
.register(r'investments', views.InvestmentViewSet, basename='startups_investment',
parents_query_lookups=['startup']),
)
Thanks for your help.
I would try something like this:
class StartUpViewSet(NestedViewSetMixin, ModelViewSet):
model = Startup
#queryset = Startup.objects.all()
serializer_class = StartupSerializer
def get_queryset(self):
Startup.objects.annotate(active_investments=Count('startup_investments', filter=Q(startup_investments__active=True)).filter(active_investments__gt=0)
Hello I am posting this answer hoping it will help others as I have spent two days to make this work!!
class ActiveStartupSerializer(serializers.ListSerializer):
def to_representation(self, data):
"""List all startups with one active investment"""
data = data.filter(startup_investments__active=True)
return super(ActiveStartupSerializer, self).to_representation(data)
class Meta:
model = Startup
fields = ('id', 'header', 'title', 'description', 'tags', 'card_image',
'logo_image', 'main_img', 'startup_investments')
class InvestmentSerializer(serializers.ModelSerializer):
class Meta:
model = Investment
fields = ('id', 'Investment_title', 'collected_amount', 'goal_percentage', 'number_of_investors',
'days_left', 'active')
class StartupSerializer(serializers.ModelSerializer):
startup_investments = InvestmentSerializer(many=True, read_only=True)
class Meta:
model = Startup
list_serializer_class = ActiveStartupSerializer
fields = ('id', 'header', 'title', 'description', 'tags', 'card_image',
'logo_image', 'main_img', 'startup_investments')

How to write query with in a model with foreign key relation?

class Categorie(models.Model):
name = models.CharField(max_length=200)
description = models.TextField(max_length=2000)
status = models.BooleanField(default=True)
added_date = models.DateTimeField(auto_now_add=True)
def __unicode__(self):
return u'%s' % self.name
class GroupQuestion(models.Model):
category = models.ForeignKey(Categorie, related_name='%(class)s_name_related', null=True)
name = models.CharField(max_length=200)
added_date = models.DateTimeField(auto_now_add=True)
status = models.BooleanField(default=True)
class Meta:
verbose_name = 'Group of Questions'
verbose_name_plural = 'Group of Questions'
def __unicode__(self):
return u'%s' % self.name
class Question(models.Model):
category = models.ForeignKey(Categorie, related_name='%(class)s_name_related', null=True)
group = models.ForeignKey(GroupQuestion, related_name='%(class)s_name_related')
name = models.TextField(max_length=200)
added_date = models.DateTimeField(auto_now_add=True)
status = models.BooleanField(default=True)
#select_choice = models.CharField(max_length=5, choices=QUESTION_CHOICES, null=True)
positive_answer = models.PositiveIntegerField()
negative_answer = models.PositiveIntegerField()
def __unicode__(self):
return u'%s' % self.name
I have these three model. When I pass category_id from my API wants to get QuestionGroups and Questions related to that group?
Some thing like this
"data": [
{
id:1
name = ABC
"question":[
{
"id":1
"name":ABC
}
{
"id":1
"name":ABC
}
]
}
{
id:1
name = ABC
"question":[
{
"id":1
"name":ABC
}
{
"id":1
"name":ABC
}
]
}
}
I am new in django some can help me how to write query in view and how to serialize data.
You are looking for a nested serialization.
You should create two serializers. One for your GroupQuestion model and one for your Question model. You will use in your QuestionSerializer inside your GroupQuestionSerializer in order to perform a nested serialization.
In your serializers.py:
from rest_framework import serializers
from .models import GroupQuestion, Question
# Serializer for the Question model
class QuestionSerializer(serializers.ModelSerializer):
class Meta:
model = Question
fields = ('id', 'name')
# Serializer for the GroupQuestion model
class GroupQuestionSerializer(serializers.ModelSerializer):
question_name_related = QuestionSerializer(read_only=True, many=True)
# The magic happens here ^
# You use your QuestionSerializer inside your GroupQuestionSerializer
# In order to serialize the related Questions for this GroupQuestion
class Meta:
model = GroupQuestion
fields = ('id', 'question_name_related')
Then let's say you have a simple ListAPIView for listing your GroupQuestion entries.
In your views.py:
from rest_framework import generics
from .models import GroupQuestion
from .serializers import GroupQuestionSerializer
# Import the serializer that we have just created
class GroupQuestionList(generics.ListAPIView):
serializer_class = GroupQuestionSerializer
def get_queryset(self):
category_id = self.kwargs['category_id']
category = generics.get_object_or_404(Categorie, id=category_id)
return GroupQuestion.objects.filter(category=category)
This view will simply serialize all your GroupQuestion models, which have related Categorie with the given id.
Finally, map this view in your urls and when you access this endpoint, you should get the expected result.
In your urls.py:
from django.conf.urls import url
from . import views
urlpatterns = [
url(r'^groups/(?P<category_id>[0-9]+)/$', views.GroupQuestionList.as_view(), name='group_question_list')
]
Note: I am not sure that question_name_related is the valid related_name for the Question model in your GroupQuestion.