0

I am trying to understand the code in relation to this great answer: Can I use JSON data to add new objects in Django?

Specifically I would like to know what the _ means in the method below.

def save(self, *args, **kwargs):

    member, _ = Member.objects.get_or_create(name = self.name)
    # can update member here with other fields that relate to them
    self.member = member
    super(Data, self).save(*args, **kwargs)

Thanks!

Community
  • 1
  • 1
BluePython
  • 1,635
  • 3
  • 24
  • 35
  • its just a common way to denote that we dont care about the second return variable just member – Joran Beasley Sep 12 '13 at 18:55
  • 3
    A valid identifier consists of alphanumeric characters and underscores, and does not begin with a number. `_` is simply the valid identifier least likely to catch your eye or have any semantic meaning, so you don't try to attach any significance to it. As such, it's perfect for when you need an identifier but don't care at all what value is assigned to it. – chepner Sep 12 '13 at 18:58
  • … and many, many other questions… – abarnert Sep 12 '13 at 19:12

2 Answers2

3

get_or_create() returns a tuple with a Model instance and created boolean flag.

_ is just a "special variable name", convention used in python for throwaway variables, see What is the purpose of the single underscore "_" variable in Python?.

You can use member = Member.objects.get_or_create(name = self.name)[0] instead if you like.

Community
  • 1
  • 1
alecxe
  • 462,703
  • 120
  • 1,088
  • 1,195
1

(in this case) its just a common way to denote that we dont care about the second return variable just member

however in the shell it serves a different purpose (the result of the last operation)

>>> 5 + 7
>>> print _
12

and it is often used in translations and localizations to handle strings that should be translated

translated = _("some text to be translated")
Joran Beasley
  • 110,522
  • 12
  • 160
  • 179
  • I would not agree with the `translated` example you have shown, You can import the ugettext as _anything_. Not only `_` – karthikr Sep 12 '13 at 18:58
  • but the common practice is to use _() because there are many programs that scrape and look for that to create your translations ... `_` is the common case, not the only one ... so common that when you google info about it every example uses it (well almost every example) and even the docs – Joran Beasley Sep 12 '13 at 18:59