Django Rest Framework-为给定的父模型及其子模型中的相关条目复制数据

时间:2018-09-03 13:17:38

标签: django django-rest-framework

我有2种型号纸张问题。用户可以选择任何论文,并可以创建该论文的副本(包括其问题)。如何在Django Rest Framework中实现呢?

models.py

class Paper(models.Model):    
    paper_name = models.CharField(max_length=128)

class Question(models.Model):
    question_text = models.CharField(max_length=1024)        
    paper_id = models.ForeignKey(Paper, related_name='questions_paper')

serializer.py

class PaperSerializer(serializers.ModelSerializer):        
    class Meta:
        fields = ('id', 'paper_name')
        model = Paper 

    def create(self, validated_data):           
        source_pape = ??  # paper whose copy to be made
        paper = Paper.objects.create(**validated_data)
        questions = Question.objects.filter(paper=source_paper)
        Question.objects.bulk_create([Question(paper=paper, question_text=question.question_text) for question in questions])
    return paper  

class QuestionSerializer(serializers.ModelSerializer):
    class Meta:
        fields = ('id', 'question_text', 'paper_id')
        model = Question

如何从用户那里获取输入source_paper(需要复制的纸张)并复制其数据?谢谢你。

1 个答案:

答案 0 :(得分:0)

尝试在创建时将 source_parer 传递给序列化程序。

class PaperSerializer(serializers.ModelSerializer):
    source_paper = serializers.CharField(write_only=True, required=True)

    class Meta:
        fields = ('id', 'paper_name', 'source_paper')
        model = Paper

    def create(self, validated_data):
        source_paper = validated_data.pop('source_paper')  # paper whose copy to be made
        paper = Paper.objects.create(**validated_data)
        questions = Question.objects.filter(paper=source_paper)
        Question.objects.bulk_create([Question(paper=paper, question_text=question.question_text) for question in questions])
        return paper