0
我有Django的REST框架如下設置:Django的REST框架外鍵 - NOT NULL約束失敗
models.py:
class Device(models.Model):
name = models.CharField()
latitude = models.FloatField()
longitude = models.FloatField()
altitude = models.FloatField()
class Event(models.Model):
id_device = models.ForeignKey(Device, related_name='events')
name = models.CharField()
date = models.CharField()
time = models.CharField()
class Values(models.Model):
id_device = models.ForeignKey(Device)
id_event = models.ForeignKey(Event, related_name='values')
x = models.FloatField()
y = models.FloatField()
z = models.FloatField()
time = models.IntegerField()
serializers.py:
class DeviceSerializer(serializers.ModelSerializer):
events = EventSerializer(many=True)
class Meta:
model = Device
fields = ('url', 'id', 'name', 'latitude', 'longitude', 'altitude', 'events')
def create(self, validated_data):
events_data = validated_data.pop('events')
device = Device.objects.create(**validated_data)
for event in events_data:
Events.objects.create(device=device, **event)
return device
class EventSerializer(serializers.ModelSerializer):
values = ValuesSerializer(many=True)
class Meta:
model = Event
fields = ('url', 'id', 'name', 'date', 'time', 'values')
def create(self, validated_data):
values_data = validated_data.pop('values')
event = Event.objects.create(**validated_data)
for value in values_data:
Values.objects.create(event=event, **value)
return event
class ValuesSerializer(serializers.ModelSerializer):
class Meta:
model = Values
fields = ('x', 'y', 'z', 'time')
當我嘗試發佈事件與一些值使用JSON文件,像這樣的分配:
{
"name": "name_example",
"date": "date_example",
"time": "time_example",
"values": [
{
"x": 1,
"y": 2,
"z": 3,
"time": 1
},
{
"x": 10,
"y": 20,
"z": 30,
"time": 2
},
{
"x": 100,
"y": 200,
"z": 300,
"time": 4
}
]
}
我得到的錯誤IntegrityError: NOT NULL constraint failed: drf_event.id_device_id
我是新來這個框架,所以我能以發佈新事件用做值分配給現有的設備?
謝謝你,這是一個很大的幫助!我還必須將此create()方法代碼行更改爲:'Values.objects.create(id_device = event.id_device,id_event = event,** value)' – limadelrey