[英]How to manually populate Django model data for insert
I'm trying to store a list of timings for a speed test. 我正在尝试存储速度测试的时间列表。
All timings are serialized clientside and sent to the server via ajax. 所有计时都在客户端序列化并通过ajax发送到服务器。
Model: 模型:
class SpeedTest(models.Model):
t1 = models.DecimalField(max_digits=9, decimal_places=6, default=None, blank=True, null=True)
t2 = models.DecimalField(max_digits=9, decimal_places=6, default=None, blank=True, null=True)
t3 = models.DecimalField(max_digits=9, decimal_places=6, default=None, blank=True, null=True)
...
...
...
t100+ = ...
View: 视图:
def save(request):
results = json.loads(request.POST.get('results'))
speed_test = SpeedTest.objects.create()
for result in results:
key = "t"+str(result['key'])
speed_test.key = value
speed_test.save()
Where results
has the form: results
的形式为:
results[0]['key'] = 1
results[0]['value'] = 0.539
results[1]['key'] = 2
results[1]['value'] = 0.654
results[2]['key'] = 3
results[2]['value'] = 0.426
...
...
...
results[100+]...
I am trying to loop through all the t1 - t100+
values and add them to my model object. 我试图遍历所有
t1 - t100+
值,并将它们添加到我的模型对象中。 Ie a loop to do: 即循环执行:
speed_test.t1 = 0.539
speed_test.t2 = 0.654
speed_test.t3 = 0.426
...
etc
These lines are not doing the job. 这些行不能胜任。
key = "t"+str(result['key'])
speed_test.key = value
What is the correct way to do this? 正确的方法是什么?
this is question is answered within a different context here How to set django model field by name? 这是在不同上下文中回答的问题。 如何通过名称设置Django模型字段? .
。
To explain it a bit further and with your code as example: 为了进一步解释,并以您的代码为例:
Construct the Fieldname via key = "t"+str(result['key'])
, 通过
key = "t"+str(result['key'])
构造字段名称,
Set the desired value via setattr(speed_test, key, result['value'])
通过
setattr(speed_test, key, result['value'])
设置所需的值
And after the loop, don't forget to call speed_test.save()
. 在循环之后,不要忘记调用
speed_test.save()
。
One personal Recomendation: 一个个人推荐:
If you are looking forward to more work correlated with AJAX/JSON you might want to consider Django-REST-Framework for it's Serializer which handle such stuff quite good for simple/flat cases (you current problem would be in such category). 如果您希望进行更多与AJAX / JSON相关的工作,则可以考虑使用Django-REST-Framework,因为它的Serializer在简单/扁平情况下处理此类内容非常有用(您当前的问题属于此类)。
NOTE: In your given example data 注意:在给定的示例数据中
results[0]['key'] = 1
results[0]['value'] = 0.539
results[1]['key'] = 2
results[1]['value'] = 0.654
results[2]['key'] = 2
results[2]['value'] = 0.426
does the third result really OVERWRITE the second ? 第三个结果是否真的覆盖了第二个?
Hope this helps. 希望这可以帮助。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.