0
我在使用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.
該死的,我從另一個角度看待這個問題。謝謝 – ivica
對不起,只好'解',因爲它只回答了部分問題。我編輯了這個問題。 – ivica