Django Rest Framework保存多部分/表单数据

时间:2019-06-26 09:03:45

标签: django django-rest-framework

我有以下模型:

class Exercise(TimeStampedModel):
    user = models.ForeignKey(
        User, on_delete=models.CASCADE, related_name='roms')
    # ... other fields
    recording = models.ManyToManyField(Recording)

Recording模型除其他字段外还包含一个名为zip_file的字段,该字段为FileField

由于这是我第一次使用DRF,而我的工作大部分是前端的,通常与Django无关,所以我很难理解如何保存这样的模型实例。这是ExerciseSerializer

class ExerciseSerializer(serializers.ModelSerializer):
    recording = RecordingSerializer()

    class Meta:
        model = Exercise
        fields = ('duration', 'recording', ...)

这是Recording模型:

class Recording(TimeStampedModel):
    user = models.ForeignKey(
        User, on_delete=models.CASCADE, related_name='recordings')
    sensors = models.ManyToManyField(Sensor)
    category = models.CharField(
        max_length=4, choices=( ... ), default=(...)
    data = JSONField(null=True, blank=True)
    zip_file = models.FileField(
        upload_to=upload_location, storage=storage, null=True)

这是RecordingSerializer

class RecordingSerializer(serializers.ModelSerializer):
    sensors = SensorSerializer(many=True)

    class Meta:
        model = Recording
        fields = ('sensors', 'category', 'data', 'zip_file')

如果我理解正确,则需要更新此RecordingSerializer以便正确保存zip_file字段。那是对的吗?还是我需要更改ExerciseSerializer中的某些内容?

0 个答案:

没有答案