Django REST框架-Many2Many / Through

时间:2018-12-13 00:13:36

标签: python django serialization django-models django-rest-framework

通常,对于以下型号的序列化器,我感到困惑。有人愿意看一下这段代码,看看是否有意义/是否需要进行某些更改才能使我的序列化程序正常工作? 我认为大多数情况下是正确的,但是我不确定如何处理Term中的ManyToMany关系以及“ through = Offering”。

这是models.py:

from django.db import models
from django.contrib.auth.models import User

class Course(models.Model):
    prefix = models.CharField(max_length=100)
    course_num = models.CharField(max_length=100)
    lecture_hours = models.CharField(max_length=20)
    lab_hours = models.CharField(max_length=20)
    credit_hours = models.CharField(max_length=20)
    date = models.DateField(auto_now=False, auto_now_add=False)
    previous_version = models.ForeignKey('self', on_delete=models.DO_NOTHING, blank=True, null=True)

    class Meta:
        ordering = ('prefix')

class Term(models.Model):
    semester = models.CharField(max_length=100)
    year = models.CharField(max_length=100)
    name = models.CharField(max_length=200)
    courses = models.ManyToManyField(Course, through='Offering', related_name='terms')

    def termCourses(self):
        term_courses = self.courses.all()
        return term_courses

class Offering(models.Model):
    term = models.ForeignKey(Term, on_delete = models.CASCADE)
    course = models.ForeignKey(Course, on_delete = models.CASCADE)
    instructor = models.ForeignKey(User, on_delete = models.CASCADE)

class TermPermission(models.Model):
    creator = models.ForeignKey(User, on_delete = models.CASCADE)
    term = models.ForeignKey(Term, on_delete = models.CASCADE)

这是serializers.py

from django.contrib.auth.models import User, Group
from .models import Course, Term, Offering
from rest_framework import serializers


class CourseSerializer(serializers.ModelSerializer)
    class Meta:
        model = Course
        fields = ('prefix,',
                  'course_num',
                  'lecture_hours',
                  'lab_hours',
                  'credit_hours',
                  'date',
                  'previous_version',
                  'terms'
                  )

class TermSerializer(serializers.ModelSerializer)
    courses = OfferingSerializer(source='offering_set', many=True)

    class Meta:
        model = Term
        fields = ('semester,',
                 'year',
                  'name',
                  'courses',
                  )

class OfferingSerializer(serializers.ModelSerializer)
    offering_term = serializers.ReadOnlyField(source='term.id')
    offering_course = serializers.ReadOnlyField(source='course.id')

class Meta:
    model = Offering
    fields = ('offering_term',
              'offering_course'
              )

1 个答案:

答案 0 :(得分:1)

如果该API适用于所列产品的条款,则应该可以使用:

from django.contrib.auth.models import User, Group
from .models import Course, Term, Offering
from rest_framework import serializers

class CourseSerializer(serializers.ModelSerializer):

    class Meta:
        model = Course
        fields = ('prefix,',
                  'course_num',
                  'lecture_hours',
                  'lab_hours',
                  'credit_hours',
                  'date',
                  'previous_version',
                  )

class OfferingSerializer(serializers.ModelSerializer):
    course = CourseSerializer(read_only=True)

    class Meta:
        model = Offering
        fields = ('course', "instructor")


class TermSerializer(serializers.ModelSerializer):
    offerings = OfferingSerializer(source="offering_set")

    class Meta:
        model = Term
        fields = ('semester,', 'year', 'name', 'offerings')

这将导致以下结果:

{
    "count": 1,
    "next": null,
    "previous": null,
    "results": [
        {
            "name": "Winter of 1993",
            "year": "1993",
            "semester": "Winter",
            "offerings": [
                {
                    "instructor": "<instructor_id>",
                    "course": {
                        "id": 1,
                        "prefix": "CS",
                        "credit_hours": "4.0",
                        "lab_hours": "2"
                    }
                },
                {
                    "instructor": "<instructor_id>",
                    "course": {
                        "id": 2,
                        "prefix": "ECON",
                        "credit_hours": "4.0",
                        "lab_hours": "0"
                    }
                },
            ]
        }
    ]
}