如何在django ModelSerializer中从请求中检索其他JSON数据

时间:2017-11-23 19:10:31

标签: python json django django-rest-framework serializer

我有一个模型序列化程序,它创建一个Program对象,以及另一个OutboundProgram对象。我收到的json包含程序对象的所有细节以及创建OutboundProgram所需的其他细节。如何检索其他字段,因为序列化程序仅读取特定对象的字段。附:我们的团队负责人不希望我使用嵌套的JSON

json收到了请求:

{
"linkage": "AP",
"name": "something",
"academic_year": 2017,
"terms_available":[1,2],
"is_graduate": false,
"requirement_deadline":"2011-10-16",
"institution": 3
}

models.py

class Program(SoftDeletionModel):
    linkage = ForeignKey(Linkage)
    name = CharField(max_length=64)
    academic_year = ForeignKey(AcademicYear)
    terms_available = ManyToManyField(Term)
    is_graduate = BooleanField()

    def __str__(self):
        return self.name


class OutboundProgram(SoftDeletionModel):
    program = ForeignKey(Program)
    requirement_deadline = DateField()
    institution = ForeignKey(Institution)

serializers.py

class OutboundProgramSerializer(ModelSerializer):
    class Meta:
        model = Program
        fields = "__all__"

    def create(self, validated_data):
        terms = validated_data.pop('terms_available')
        program = Program.objects.create(**validated_data)
        for term in terms:
            program.terms_available.add(term)
        program.save()

        outbound_program = OutboundProgram.objects.create(program=program)
        #how to assign outbound_program.requirements_deadline from json
        return program

任何形式的帮助都会有用。谢谢!

2 个答案:

答案 0 :(得分:0)

尝试使用{{3}}:

request = self.context['request']
terms = request.data.get('terms_available', [])

答案 1 :(得分:0)

<强> serializers.py

class OutboundProgramSerializer(ModelSerializer):
    requirement_deadline = serializers.DateField(write_only=True)
    institution = serializers.IntegerField(write_only=True)
    class Meta:
        model = Program
        fields = "__all__"

    def create(self, validated_data):
        terms = validated_data.pop('terms_available')
        program = Program.objects.create(**validated_data)
        for term in terms:
            program.terms_available.add(term)
        program.save()

        outbound_program = OutboundProgram.objects.create(program=program)
        outbound_program.requirement_deadline = validated_data.pop('requirement_deadline')
        outbound_program.institution_id = validated_data.pop('institution')
        outbound_program.save()
        return program