Django不允许获取/创建新对象:QuerySet对象没有属性get_or_create

时间:2014-03-09 16:53:29

标签: python django postgresql

我在PostgreSQL上使用Python 3.2和Django 1.6.2 当尝试使用get_or_create快捷方式有条件地创建对象时,我得到AttributeError

当然,解决方法是在尝试获取对象然后创建它时捕获异常。但是可以使用常规get_or_create吗?

'QuerySet' object has no attribute 'get_or_create'
Traceback (most recent call last):

  File "/Users/urk/Documents/virtualenv/pycharm_python_3_3/lib/python3.3/site-packages/tastypie/resources.py", line 195, in wrapper
    response = callback(request, *args, **kwargs)

  File "/Users/urk/Documents/virtualenv/pycharm_python_3_3/lib/python3.3/site-packages/tastypie/resources.py", line 426, in dispatch_list
    return self.dispatch('list', request, **kwargs)

  File "/Users/urk/Documents/virtualenv/pycharm_python_3_3/lib/python3.3/site-packages/tastypie/resources.py", line 458, in dispatch
    response = method(request, **kwargs)

  File "/Users/urk/Documents/virtualenv/pycharm_python_3_3/lib/python3.3/site-packages/tastypie/resources.py", line 1320, in post_list
    updated_bundle = self.obj_create(bundle, **self.remove_api_resource_names(kwargs))

  File "/Users/urk/Documents/xxx/app/api/userresource.py", line 51, in obj_create
    api_key, created = ApiKey.objects.get_or_create(user=rv.obj)

  File "/Users/urk/Documents/virtualenv/pycharm_python_3_3/lib/python3.3/site-packages/django/db/models/manager.py", line 154, in get_or_create
    return self.get_queryset().get_or_create(**kwargs)

AttributeError: 'QuerySet' object has no attribute 'get_or_create'

编辑:代码示例。 来自python manage.py shell的以下代码提供了异常

from django.contrib.auth.models import User
User.objects.get_or_create(username='tu')

Traceback (most recent call last):
  File "<console>", line 1, in <module>
  File "/Users/urk/Documents/virtualenv/pycharm_python_3_3/lib/python3.3/site-packages/django/db/models/manager.py", line 154, in get_or_create
    return self.get_queryset().get_or_create(**kwargs)
AttributeError: 'QuerySet' object has no attribute 'get_or_create'

1 个答案:

答案 0 :(得分:0)

按照@AndreyNelubin的建议重新创建虚拟环境解决了这个问题。