>>> queryset = User.objects.filter(
Q(first_name__startswith='R') | Q(last_name__startswith='D')
)
>>> queryset
<QuerySet [<User: Ricky>, <User: Ritesh>, <User: Radha>, <User: Raghu>, <User: rishab>]>
>>> queryset = User.objects.filter(
Q(first_name__startswith='R') & ~Q(last_name__startswith='Z')
)
SELECT "auth_user"."id",
"auth_user"."password",
"auth_user"."last_login",
"auth_user"."is_superuser",
"auth_user"."username",
"auth_user"."first_name",
"auth_user"."last_name",
"auth_user"."email",
"auth_user"."is_staff",
"auth_user"."is_active",
"auth_user"."date_joined"
FROM "auth_user"
WHERE ("auth_user"."first_name"::text LIKE R%
AND NOT ("auth_user"."last_name"::text LIKE Z%))
프로젝트시 로그인 구현할때 아이디와 이메일 모두 체크하여야 하는 상황해서 사용할 수 있을텐데요.
코드보면서 확인하고 마무리하겠습니다.
from django.db.models import Q
class SignInView(View):
def post(self, request):
data = json.loads(request.body)
login_id = data.get('login_id', None)
email = data.get('email', None)
try:
if User.objects.filter(Q(login_id = login_id)|Q(email=email)).exists():
user = User.objects.filter(Q(login_id = login_id)|Q(email = email))[0]
if bcrypt.checkpw(data['password'].encode('utf-8'), user.password.encode('utf-8')):
token = jwt.encode({'login_id':user.login_id}, SECRET_KEY, algorithm = 'HS256')
return JsonResponse({"token":token.decode('utf-8')}, status = 200)
return HttpResponse(status = 401)
return HttpResponse(status = 400)
except KeyError:
return JsonResponse({"message":"INVALID_KEYS"}, status = 400)