Reputation: 824
I have a query I am making in a django view.py file. I want to use 'or' and 'and' statements in the query. I am getting a message that says 'or_' is not defined and I was wondering what the import statement is for that because I can not find it anywhere.
Here is the query:
@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)
Here is the error:
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
Upvotes: 1
Views: 80
Reputation: 363566
At a guess, the import is likely intended from stdlib operator
module. But the code is missing the necessary Q
objects to use the operator functions in such a fashion.
This looks more to me like code written by someone who doesn't know how to use Django ORM very well. Rewrite it like this, no Q
nor operator
functions are necessary for such a simple query:
friends = Friends.objects.filter(user=user.username, friends=view)
friends |= Friends.objects.filter(user=view.username, friends=user)
Upvotes: 1