保存相关对象

时间:2015-12-13 15:56:53

标签: python django django-rest-framework

我在使用Django Rest Framework保存相关对象时遇到了一些麻烦。这是我的模特

# models.py
class PowerStatus(models.Model):
    status = models.CharField(max_length=50)

class VirtualMachine(models.Model):
    power_status = models.ForeignKey(PowerStatus, verbose_name='Power status')

我的序列化器看起来像这样:

# serializers.py
class PowerStatusSerializer(serializers.ModelSerializer):
    status = serializers.CharField(max_length=30)

    class Meta:
        model = PowerStatus

class VMSerializer(serializers.ModelSerializer):
    power_status = PowerStatusSerializer()

    class Meta:
        model = VirtualMachine

    def create(self, validated_data):
        power_status_data = validated_data.pop('power_status')
        vm = VirtualMachine.objects.create(**validated_data)
        PowerStatus.objects.create(vm=vm, **power_status_data)

        return vm

我得到的错误是:django.db.utils.IntegrityError: (1048, "Column 'power_status_id' cannot be null")

我关注http://www.django-rest-framework.org/api-guide/serializers/#dealing-with-nested-objects,但我做错了。

:编辑:

在处理Column cannot be null之后,又出现了另一个问题;

ValueError: Cannot assign "OrderedDict([('status', 'Running')])": "VirtualMachine.power_status" must be a "PowerStatus" instance.

1 个答案:

答案 0 :(得分:1)

在VirtualMachine模型中,将null = True传递给power_status字段。

class VirtualMachine(models.Model):
    power_status = models.ForeignKey(PowerStatus, verbose_name='Power status', null=True)