Django Python - What does _ do after a variable name

ghz 8months ago ⋅ 78 views

Sorry for my poor explanation but I'm reviewing my professor's code like this:

              user, _ = User.objects.get_or_create(
                      name = serializer.data['name'],
                      email = serializer.data['email'],
                      password = make_password(serializer.data['password']))

when I remove the ", _" from that I can't access the objects (eg: name) of it. I was doing "user.name" but I cant without the ", _" can someone explain why that is. It's my first time here in in SO hehe

I wanna access the name field through the user where I assigned the object I created

Answers

In Python, when you use the get_or_create method of a Django model's manager, it returns a tuple containing two elements: the first element is the object retrieved or created, and the second element is a boolean indicating whether the object was created or not (True if it was created, False otherwise).

In your code snippet:

user, _ = User.objects.get_or_create(
    name=serializer.data['name'],
    email=serializer.data['email'],
    password=make_password(serializer.data['password']))

You are unpacking this tuple into two variables: user and _. The _ variable is a convention in Python to denote a variable that is used to discard the value. In this case, it is used to discard the boolean indicating whether the object was created or not. You can access the name field through the user variable:

user_name = user.name

If you remove the , _ part from your code, you will not be unpacking the boolean value, and therefore, you will not be able to access the name field through the user variable directly, because it will contain the tuple instead of just the object. Instead, you would need to access it like this:

user_name = user[0].name

However, using _ to discard values is a common convention in Python when you're not interested in using a particular value from a tuple or any iterable. It makes the code more readable and concise.