Django模型在查询中读取和创建?

时间:2015-12-30 06:57:04

标签: python sql django

我想根据模型的最后一个ID在Django模型中插入一行。我的查询就像,

Order.objects.create(group=123131, identifier=friendly_invoice.encode(Order.objects.last().id))
# group and identifier are unique together

我记录了http://www.dabapps.com/blog/logging-sql-queries-django-13/

中显示的查询
(0.016) SELECT `order`.`id`, `order`.`group`, `order`.`identifier`, `order`.`created`, `order`.`modified` FROM `order` ORDER BY `order`.`id` DESC LIMIT 1; args=()
DEBUG 2015-12-30 12:16:21,881 (0.016) SELECT `order`.`id`, `order`.`group`, `order`.`identifier`, `order`.`created`, `order`.`modified` FROM `order` ORDER BY `order`.`id` DESC LIMIT 1; args=()
DEBUG 2015-12-30 12:16:21,881 (0.016) SELECT `order`.`id`, `order`.`group`, `order`.`identifier`, `order`.`created`, `order`.`modified` FROM `order` ORDER BY `order`.`id` DESC LIMIT 1; args=()
(0.000) INSERT INTO `order` (`group`, `identifier`, `created`, `modified`) VALUES ('123131', '378ETGY', '2015-12-30 06:46:21', '2015-12-30 06:46:21'); args=[u'123131', '378ETGY', u'2015-12-30 06:46:21', u'2015-12-30 06:46:21']
DEBUG 2015-12-30 12:16:21,881 (0.000) INSERT INTO `order` (`group`, `identifier`, `created`, `modified`) VALUES ('123131', '378ETGY', '2015-12-30 06:46:21', '2015-12-30 06:46:21'); args=[u'123131', '378ETGY', u'2015-12-30 06:46:21', u'2015-12-30 06:46:21']
DEBUG 2015-12-30 12:16:21,881 (0.000) INSERT INTO `order` (`group`, `identifier`, `created`, `modified`) VALUES ('123131', '378ETGY', '2015-12-30 06:46:21', '2015-12-30 06:46:21'); args=[u'123131', '378ETGY', u'2015-12-30 06:46:21', u'2015-12-30 06:46:21']

这是在db中创建两个sql查询。我相信如果这个代码由两个并行请求执行,这将会出错。

如何以更安全的方式编写此查询?

1 个答案:

答案 0 :(得分:0)

我使用https://docs.djangoproject.com/en/1.7/topics/db/transactions/#savepoints

解决了这个问题
from django.db import transaction

# open a transaction
@transaction.atomic
def viewfunc(request):
   ...