2

I would like to check if the username given during the registration of a user already exists using pymodm with a clear solution similar to this one using pymongo:

if users.find_one({"username": username}) is not None:
     print("This username already exists")

To make this code I would have to write :

try :
    user = User.objects.get({'username': username})
except errors.DoesNotExist:
    user = None
if user is not None:
    print("This username already exists")

Because pymodm uses expections. It is very inefficient and heavy to code. Do you have any idea ?

Evhz
  • 8,852
  • 9
  • 51
  • 69
AlixL
  • 372
  • 2
  • 13
  • `count()` will count the number of entry in the returned `get()` request. However the get request already raises an exception when no data is available. – AlixL Apr 22 '18 at 19:56
  • `count()` is not using the index that the username (*should be an indexed attribute in order to use the index db joy*) so you need to assess how many users are in total (not optimal) instead of just finding one using an indexed field. This can make your login action a paradise for coffee. – Evhz Apr 25 '18 at 11:04

1 Answers1

0

Well, yes, threading is not the most optimal way, but, in this case, it's slightly the same effect than to keep open a listener waiting for a callback when the db request is ready.

Your code is redundant, as the exception already checks your if statement. Do it like:

try :
     user = User.objects.get({'username': username})
     print("This username already exists")
except errors.DoesNotExist:
     # You can create the user     
     print("This username can be used")

And also think about creating an index in the username field, or, perform the user find operation using an indexed field you may already have, which will make your application nicer in terms of performance.

Evhz
  • 8,852
  • 9
  • 51
  • 69