Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    primarykey
    data
    text
    <p>Django's models gives a convenience method called <a href="https://docs.djangoproject.com/en/dev/ref/models/querysets/#get-or-create" rel="nofollow"><code>get_or_create</code></a>, which looks up for an object based on specified criteria (in <code>kwargs</code>). If the criteria do not match, a new object is created.</p> <p>Now, there is no way for us to determine in the view if the object returned was created or pre-existing (especially if you dont have a <code>created_datetime</code> or similar field), hence the <code>created</code>. It is a boolean variable, which is set to <code>True</code> if a new object was created by the ORM, and set to <code>False</code> if an existing object was retrieved. </p> <p>Now, in your scenario:</p> <pre><code>obj, created = Person.objects.get_or_create(first_name=’John’, last_name=’Lennon’, defaults={’birthday’: date(1940, 10, 9)}) </code></pre> <p>This is saying, get me the <code>Person</code> object with <code>first_name = John, last_name = Lennon, birthday = ...</code></p> <p>If this is not found, create a new one for me. </p> <p>The <code>defaults</code> specify the initial value of the field <code>birthday</code> while creating the object in this scenario.</p> <p>This is also equivalent of writing</p> <pre><code>obj = None try: obj = Person.objects.get(first_name=’John’, last_name=’Lennon’) except Person.DoesNotExist: obj = Person.objects.create(’birthday’ = date(1940, 10, 9), first_name='John', last_name = 'Lennon') </code></pre> <p>In the signal's receiver, <code>kwargs</code> is a dictionary with custom key-value pairs. When you look at the signals' documentation, lets say <code>post_save</code> has the following signature</p> <pre><code>django.db.models.signals.post_save post_save(sender, instance, created, raw, using, update_fields) </code></pre> <p>This s the same as</p> <pre><code>post_save(sender, **kwargs) #where the rest of the args are a dictionary saved in **kwargs </code></pre> <p>Here, <code>created</code> has a similar meaning. It is notifying the signal whether <code>instance</code> was newly created, or updated. </p> <p>So, if <code>created = True</code>, new object was created. <code>created=False</code>, object was probably updated. </p>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. VO
      singulars
      1. This table or related slice is empty.
    2. VO
      singulars
      1. This table or related slice is empty.
    3. VO
      singulars
      1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload