Django DRF Serializer不保存嵌套模型:我错过了什么?

f0brbegy  于 2023-05-30  发布在  Go
关注(0)|答案(1)|浏览(86)

Django DRF嵌套序列化程序保存问题

我不能保存我的模型由于一些嵌套序列化id问题,我将共享我的模型

class Duration(models.Model):
    start_time = models.PositiveIntegerField(blank=True,null=True)
    end_time = models.PositiveIntegerField(blank=True,null=True)

    def __str__(self):
        self.end_time

class VideoMaker(models.Model):
    CHOICE_SELECT = [
        ('vo','voice over'),
        ('bg_music','backgournd music'),
        ('video_music','vidio music'),
    ]
    typee = models.CharField(max_length=15,choices=CHOICE_SELECT)
    high_volume = models.PositiveIntegerField()
    low_volume = models.PositiveIntegerField()
    video_component_id = models.CharField(max_length=300,null=True,blank=True)
    url = models.URLField(blank=True,null=True)
    duration = models.ForeignKey(Duration, on_delete=models.CASCADE)

    def __str__(self):
        return self.id

我的序列化程序:

class DuratinSeriaizer(serializers.ModelSerializer):
    class Meta:
        model = Duration
        fields = [
            'id',
            'start_time',
            'end_time',
        ]

class VideoMakerSerializer(serializers.ModelSerializer):
    duration = DuratinSeriaizer()
    class Meta:
        model = VideoMaker
        fields = [
            'id',
            'typee',
            'high_volume',
            'low_volume',
            'video_component_id',
            'url',
            'duration',
        ]

    def create(self, validated_data):
        datas = validated_data.pop('duration')
        duration_data = VideoMaker.objects.create(**validated_data)
        for datas in datas:
            Duration.objects.create(duration=duration_data,**datas)
        Duration.save()
        return duration_data

我的观点:

class AudioCreateApiView(generics.ListCreateAPIView):
    queryset = VideoMaker.objects.all()
    serializer_class = VideoMakerSerializer

如果我错了请帮我!
获取“NOT NULL”约束失败的错误:VideoMaker_videomaker.duration_id '''我无法保存,我很无助
我期待:

{
        "id": 6,
        "typee": "vo",
        "high_volume": 65,
        "low_volume": 123,
        "video_component_id": "wertyuio",
        "url": "",
        "duration": {
            "id": 9,
            "start_time": 21,
            "end_time": 98
        }
    }
8hhllhi2

8hhllhi21#

def create(self, validated_data):
    import pdb;pdb.set_trace()
    datas = validated_data.pop('duration')
    instance = Duration.objects.create(**datas)
    duration_data = VideoMaker.objects.create(duration=instance,**validated_data)
    return duration_data

在VideoMaker模型中,u给予了外部,因此必须将示例分配给VideoMaker表。使用import pdb;pdb.set_trace()调试代码。

相关问题