I have two models:
modesl.py
class ForumSection(models.Model):
title = models.CharField(max_length=20)
description = models.CharField(max_length=300)
order = models.IntegerField(default=0)
def __str__(self):
return self.title
class ForumSubSection(models.Model):
section = models.ForeignKey(ForumSection, on_delete=models.CASCADE)
title = models.CharField(max_length=20)
description = models.CharField(max_length=300)
order = models.IntegerField(default=0)
def __str__(self):
return self.title
I try to serialize subsections to json and return to frontend:
def ajax_create_forum_subsection(request):
.......
sections = ForumSubSection.objects.all().order_by('pk')
data = serialize("json", sections, fields=('pk', 'title', 'description', 'order', 'section'))
return JsonResponse(data, safe=False)
But ``section``` return primary key (ID of record).
I'm readed 100500 questions on SA, some peoples say to write custom serializers.
ok, I'm write it.
serializers.py
from rest_framework import serializers
from .models import *
class ForumSectionSerializer(serializers.ModelSerializer):
class Meta:
model = ForumSection
fields = '__all__'
def create(validated_data):
return ForumSection.objects.create(**validated_data)
class ForumSubSectionSerializer(serializers.ModelSerializer):
section = ForumSectionSerializer(read_only=True)
class Meta:
model = ForumSubSection
fields = ['pk', 'title', 'description', 'order', 'section']
depth = 1
def create(validated_data):
return ForumSubSection.objects.create(**validated_data)
And try to use it.
def ajax_edit_forum_subsection(request):
.......
qs = ForumSubSection.objects.all().order_by('pk')
ser = ForumSubSectionSerializer(qs)
data = ser.serialize("json", qs, fields=('pk', 'title', 'description', 'order', 'section'))
return JsonResponse(data, safe=False)
It call Server error 500 and not work.
Now is 5'th day of this problem and I write here to ask help.
How to serialize ForumSubSection objects with ForumSection objects?
CodePudding user response:
I think it should be:
def ajax_edit_forum_subsection(request):
.......
qs = ForumSubSection.objects.all().order_by('pk')
ser = ForumSubSectionSerializer(qs, many=True)
return JsonResponse(ser.data, safe=False)
CodePudding user response:
ser = ForumSubSectionSerializer(qs, many=True)
already serializes the data for you. All you need to do is: get the data from it with ser.data
or you may access the data
directly from the class ForumSubSectionSerializer(qs, many=True).data
.
def ajax_edit_forum_subsection(request):
qs = ForumSubSection.objects.all().order_by('pk')
ser = ForumSubSectionSerializer(qs, many=True).data # <- data here
return JsonResponse(ser, safe=False)
Notice the many=Trye
parameter. If a representation should be a list of items, you should pass the many=True
flag to the serializer.