我如何使用Drf序列化器将数据序列化为JSON

时间:2019-06-28 17:33:25

标签: django django-rest-framework

我有类似的数据模型:

from django.db import models


class Student(models.Model):
    first_name = models.CharField(max_length=50)
    last_name = models.CharField(max_length=50)
    email = models.EmailField()

    def __str__(self):
        return self.first_name + ' ' + self.last_name


class Course(models.Model):
    name = models.CharField(max_length=255)
    description = models.TextField()
    start_date = models.DateField(null=True)
    end_date = models.DateField(null=True)

    def __str__(self):
        return self.name


class CourseParticipant(models.Model):
    course = models.ForeignKey(Course, related_name='courses', on_delete=None)
    student = models.ForeignKey(Student, related_name='students', on_delete=None)
    completed = models.BooleanField(null=True, default=False)

    def __str__(self):
        return self.course

我有一些序列化器,例如:

class CourseSerializer(serializers.ModelSerializer):
    class Meta:
        model = Course
        fields = ('name', 'end_date', 'start_date')

我需要在json中返回数据,例如:

{
    "courses": [
        {
            "name": "Math",
            "end_date": "2019-06-26",
            "start_date": "2019-06-26",
            "participant_students_count: 10
        }
    ]
}

如何获取“ participant_students_count”并将其数据与其他字段一起返回json。

感谢帮助!

2 个答案:

答案 0 :(得分:1)

您可以使用DRF序列化器字段的SerializerMethodField。另外,请参阅有关如何遵循Backward对外键关系的访问。

from rest_framework import serializers

class CourseSerializer(serializers.ModelSerializer):
    participant_students_count = serializers.SerializerMethodField()
    class Meta:
        model = Course
        fields = ('name', 'end_date', 'start_date', 'participant_students_count')

    def get_participant_students_count(self, obj):
        return obj.courseparticipant_set.count()

答案 1 :(得分:1)

Map(abc -> ListBuffer(file:/Users/xxxxxx/path/country=abc, file:/Users/xxxxxx/path/country=abc/state=4), xyz -> ListBuffer(file:/Users/xxxxxx/path/country=xyz, file:/Users/xxxxxx/path/country=xyz/state=1, file:/Users/xxxxxx/path/country=xyz/state=6, file:/Users/xxxxxx/path/country=xyz/state=3, file:/Users/xxxxxx/path/country=xyz/state=4, file:/Users/xxxxxx/path/country=xyz/state=5, file:/Users/xxxxxx/path/country=xyz/state=2))