如何在另一个视图中访问Django Model对象?

时间:2018-06-11 12:40:44

标签: python django python-3.x transactions django-rest-framework

我有这样的代码:

def my_view(request):
    # ...
    data=Data.object.create(xyx)
    data.id   # here data.id=20
    time.sleep(600) # here sleep 600 sec
    # within 10 min how can i get data oject in another view. 
    return HttpResponse("Done")

在完成10分钟之前,我尝试在shell中获取数据对象,但数据不存在为什么?

 >>> Data.objects.get(id=20)
    Traceback (most recent call last):
      File "<console>", line 1, in <module>
      File "/home/rails/projects/zyz/xyz/lib/python3.5/site-packages/django/db/models/manager.py", line 85, in manager_method
        return getattr(self.get_queryset(), name)(*args, **kwargs)
      File "/home/rails/projects/xyz/xyz1.12/lib/python3.5/site-packages/django/db/models/query.py", line 380, in get
        self.model._meta.object_name
   data.models.DoesNotExist: Transfer matching query does not exist.
    >>> 
  

QUES。如何在anohter视图中获取与id = 20相对应的数据对象   在返回HttpResponse之前(意味着在10分钟内)。

我得到data.models.DoesNotExist我认为因为Data对象没有在数据库上提交。

提前致谢。

1 个答案:

答案 0 :(得分:-1)

您可以将创建调用包装在事务

from django.db import transaction

def viewfunc(request):
    # This code executes in autocommit mode (Django's default).

    with transaction.atomic():
        # This code executes inside a transaction.
        # create here