如何在嵌套串行器DRF中使用POST推送平面数据

时间:2018-10-24 21:53:37

标签: django django-rest-framework

我有一个可以创建测试运行的API,但是我需要一个仪器序列号来创建它。

我希望能够收到此POST请求:

{
    "serial_number":"4331214L"
    "operator": "John Doe"
}

但是,现在我必须要做:

{
    "instrument": {
        "serial_number":"4331214L"
    },
    "operator": "John Doe"
}

当前模型:

class InstrumentModel(models.Model):
    class Meta:
        db_table = "instruments"
        verbose_name = "Instrument"

    serial_number = models.CharField(max_length=10, unique=True, db_index=True)

    def __str__(self):
        return self.serial_number


class TestRun(models.Model):
    class Meta:
        db_table = "test_runs"
        verbose_name = "Test run"

    operator = models.CharField(max_length=70)
    instrument = models.ForeignKey(InstrumentModel, related_name="instruments", db_column="instrument", on_delete=models.CASCADE)
    created_at = models.DateTimeField(db_index=True, default=timezone.now)

我尝试了深度元字段。那不行也许不是在序列化器级别?

class TestRunSerializer(serializers.ModelSerializer):
    instrument = InstrumentSerializer()

    class Meta:
        model = TestRun
        fields = ('operator', 'instrument')
        depth = 1

    def create(self, validated_data):
        serial_number = validated_data.pop('serial_number')
        instrument, _ = InstrumentModel.objects.get_or_create(serial_number=serial_number)
        return TestRun.objects.create(**validated_data, instrument=instrument)

1 个答案:

答案 0 :(得分:0)

如果您使用to_internal_value

,我认为可能是正确的
class TestRunSerializer(serializers.ModelSerializer):
    instrument = InstrumentSerializer()

    class Meta:
        model = TestRun
        fields = ('operator', 'instrument')
        depth = 1
   def to_internal_value(self, data):
        serial_number = obj.get('serial_number')
        if not serial_number:
             raise serializers.ValidationError({
            'serial_number': 'This field is required.'
        })
        data['insturment'] = {'serial_number': serial_number}
        return data