包含外键的http POST并保存

时间:2018-09-08 20:39:33

标签: django database python-3.x

我从客户端发送http请求帖子。 代码客户端。

import requests
payload = {'data':['12', '15'], 'timestamp':['1', '2'], 'mission':['Mission01', 'Mission01']}
r = requests.post("http://127.0.0.1:8000", data=payload)
print(r.url)

我在Django http帖子中收到

我的模型。py

from django.db import models

class Mission(models.Model):
    name = models.CharField(max_length=250)
    description = models.CharField(max_length=1000)
    type = models.CharField(max_length=500)
    date = models.DateField()

    def __str__(self):
        return self.name + '-' + self.description

class SensorLog (models.Model):
    mission = models.ForeignKey(Mission, on_delete=models.CASCADE)
    data = models.CharField(max_length=50)
    timestamp = models.CharField(max_length=50)

我的views.py

from django.shortcuts import render
from django.http import Http404, HttpResponse
from django.views.decorators.csrf import csrf_exempt
from .models import Mission, SensorLog

@csrf_exempt
def home(request):
    context = {'request_method': request.method}
    if request.method == 'POST':
        datas = request.POST.getlist('data')
        timestamps = request.POST.getlist('timestamp')
        missions = request.POST.getlist('mission')
        for i in range(len(datas)):
           post = SensorLog.objects.create(data=datas[i], timestamp=timestamps[i], mission=missions[i])
    return render(request, 'your_template_name_here', context)

如果我运行django和client。 在Django中,我有错误:

ValueError: Cannot assign "'Mission01'": "SensorLog.mission" must be a "Mission" instance.

为什么我不保存数据?为什么我会有这个错误? 我该怎么办?

1 个答案:

答案 0 :(得分:2)

问题在于,当您使用SensorLog.objects.create(data=datas[i], timestamp=timestamps[i], mission=missions[i])时,构造函数期望一个Mission实例,但是您要提供一个字符串。

要解决此问题,您可以在名称前查找Mission,也可以只传入Mission的ID,然后在mission_id中使用SensorLog关键字arg构造函数。

使用名称(在您的home方法中):

for i in range(len(datas)):
    mission = Mission.objects.get(name=missions[i])
    post = SensorLog.objects.create(data=datas[i], timestamp=timestamps[i], mission=mission)

使用ID:

payload = {'data':['12', '15'], 'timestamp':['1', '2'], 'mission_ids':[1, 2]}

然后使用home方法:

for i in range(len(datas)):
    post = SensorLog.objects.create(data=datas[i], timestamp=timestamps[i], mission_id=mission_ids[i])