嵌套序列化程序如何覆盖create()和update()方法具有三个外键

时间:2019-06-22 06:11:16

标签: django serialization django-rest-framework django-rest-viewsets drf-writable-nested

您好,我是Django rest-framework中的新手,我想覆盖三种模型的更新和创建方法

model.py

from django.db import models

# Create your models here.

class Subject(models.Model):
    subject_name = models.CharField('Subject',max_length=20)

    def __str__(self):
        return self.subject_name 


class Person(models.Model):
    name = models.CharField(max_length=50)
    age = models.PositiveIntegerField()
    male = models.CharField(max_length=20)
    dob = models.DateField()

    def __str__(self):
        return self.name

class Marks(models.Model):

    subject = models.ForeignKey(Subject , on_delete=models.CASCADE)
    student = models.ForeignKey(Person, related_name = 'marks' , on_delete=models.CASCADE)
    term1 = models.IntegerField()
    term2 = models.IntegerField()
    final = models.IntegerField()

    def __unicode__(self):
        return self.subject

serializers.py

from rest_framework import serializers
from . import models 
from .models import Person, Marks, Subject

class SubjectSerializer(serializers.ModelSerializer):

    class Meta:
        model = Subject
        fields =  "__all__"

class MarksSerializer(serializers.ModelSerializer):

    subject = serializers.CharField()

    class Meta:
        model = Marks
        fields = ('subject','term1','term2','final')
        #depth = 1

class PersonSerializer(serializers.ModelSerializer):

    class Meta:
        model = Person

        fields = ('id', 'name','age', 'male', 'dob')

# making combine serializer for person and marks
class CombineSerializer(serializers.ModelSerializer):

    marks = MarksSerializer(many= True )

    class Meta:
        model = Person

        fields = ('id', 'name','age', 'male', 'dob','marks')

    def create(self, validated_data):
        marks = validated_data.pop('marks')
        subject = marks['subject']
        person = Person.objects.create(**validated_data)

        for marks in marks:
            Marks.objects.create(person=Person, **marks)
        return Marks

我知道如何为两个模型覆盖创建方法,但是有三个模型,并且所有模型都通过外键相互连接。我想插入像这样的数据:

[
    {
        "id": 9,
        "name": "javed",
        "age": 2,
        "male": "true",
        "dob": "2019-06-19",
        "marks": [
            {
                "subject": "Maths",
                "term1": 9,
                "term2": 16,
                "final": 8
            }
        ]
    },

0 个答案:

没有答案