M
M
Mikhail2018-08-19 08:43:16
Django
Mikhail, 2018-08-19 08:43:16

Why can't I bind a serializer to another serializer?

Good afternoon! :)
My task is when I make a request to api get_pages to get not only pages, but also texts attached to them. (I know that you need to filter by "texts_of_page" there, but at least I'll learn how to simply bind) I
did this according to the documentation, but the texts field is not displayed
models.py

from django.db import models
from django.core.validators import FileExtensionValidator

# Create your models here.

class Page(models.Model):
    class Meta:
        db_table = "pages"
    title = models.CharField(max_length=200, default="Page with media")
    texts = ""
    def __str__(self):
        return self.title + " (%s)" % str(self.id)

class Text(models.Model):
    class Meta:
        db_table = "texts"
    text = models.TextField()
    counter_views = models.IntegerField(default=0, editable=False)
    texts_of_page = models.ForeignKey(Page, on_delete=models.CASCADE)
    created_at = models.DateTimeField(auto_now_add=True)

serializers.py
from rest_framework import serializers
from main_page.models import Page, Text


class TextsSerializer(serializers.ModelSerializer):
    class Meta:
        model = Text
        fields = '__all__'

class PagesSerializer(serializers.ModelSerializer):
    texts = TextsSerializer(many=True, read_only=True)
    class Meta:
        model = Page
        fields = ('id', 'title', 'texts',)

views.py
from django.shortcuts import render_to_response
from main_page.models import Page, Text, Audio, Video
from rest_framework import generics
from .serializers import PagesSerializer, TextsSerializer


class ListPagesView(generics.ListAPIView):
    queryset = Page.objects.all()
    serializer_class = PagesSerializer

class ListTextsView(generics.ListAPIView):
    queryset = Text.objects.all()
    serializer_class = TextsSerializer

urls.py
from django.urls import path, re_path, include

urlpatterns = [
    re_path('api/(?P<version>(v1|v2))/get_pages', include('main_page.views')[0].ListPagesView.as_view()),
    re_path('api/(?P<version>(v1|v2))/get_texts', include('main_page.views')[0].ListTextsView.as_view()),
]

Answer the question

In order to leave comments, you need to log in

1 answer(s)
M
Mykola, 2018-08-19
@TheMaxai

Maxim You didn't do it according to the documentation, or you did what is more convenient for you :)
You can link serializers by the primary key. It is listed in your model. But in the serializer you refer to another field.
This will work if the primary key field is equal to the name of the serializer field.
In your case, you need to add:
for 1 element:
for several in the Text class, make a change:
in PagesSerializer rewrite
if related_name otherwise (as I wrote above) you will need to add the parameter source='new_related_name'

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question