django - 或_未定义

时间:2018-05-24 22:03:26

标签: python django django-views

我在django view.py文件中进行了查询。我想在查询中使用'或'和'和'语句。我收到一条消息,说'or_'没有定义,我想知道导入语句是什么,因为我无法在任何地方找到它。

以下是查询:

@login_required(login_url='/login/')
def user_profile(request, username):
    user = request.user
    view = User.objects.filter(username = username).first()
    view_profile = Profile.objects.filter(user = view).first()
    friends = Friends.objects.filter(or_(
                                        and_(user = user.username, friends = view),
                                        and_(user = view.username, friends = user)
                                    ))
    print(friends)
    parameters = {
        'user':user,
        'view':view,
        'view_profile':view_profile,
        'friends':friends,

    }
    return render(request, 'users/view_profile.html', parameters)

这是错误:

Internal Server Error: /assad/
Traceback (most recent call last):
  File "/Users/omarjandali/anaconda3/envs/MySplit/lib/python3.6/site-packages/django/core/handlers/exception.py", line 35, in inner
    response = get_response(request)
  File "/Users/omarjandali/anaconda3/envs/MySplit/lib/python3.6/site-packages/django/core/handlers/base.py", line 128, in _get_response
    response = self.process_exception_by_middleware(e, request)
  File "/Users/omarjandali/anaconda3/envs/MySplit/lib/python3.6/site-packages/django/core/handlers/base.py", line 126, in _get_response
    response = wrapped_callback(request, *callback_args, **callback_kwargs)
  File "/Users/omarjandali/anaconda3/envs/MySplit/lib/python3.6/site-packages/django/contrib/auth/decorators.py", line 21, in _wrapped_view
    return view_func(request, *args, **kwargs)
  File "/Users/omarjandali/Desktop/demo/mysplit/users/views.py", line 174, in user_profile
    friends = Friends.objects.filter(or_(
NameError: name 'or_' is not defined

1 个答案:

答案 0 :(得分:1)

猜测,导入可能来自stdlib operator模块。但是代码缺少以这种方式使用运算符函数所必需的Q objects

对于我来说,这更像是由不熟悉如何使用Django ORM的人编写的代码。像这样重写它,这样一个简单的查询不需要Qoperator函数:

friends  = Friends.objects.filter(user=user.username, friends=view) 
friends |= Friends.objects.filter(user=view.username, friends=user)