Reputation: 3611
Will someone please explain to me about created
, and where and how its being used in django.
I have seen it using in something like this:
obj, created = Person.objects.get_or_create(first_name=’John’, last_name=’Lennon’, defaults={’birthday’: date(1940, 10, 9)})
And even in signals:
@receiver(post_save, sender=Article)
def create_approval(sender, **kwargs):
if kwargs.get("created", False):
approval = Approval.objects.create(article_id=kwargs.get('instance').id)
I really need to know this. Any help will be much appreciated. Thank you.
Edit:
Here, from the above codes:
if kwargs.get("created", False):
What does created
mean here? Does it specify the value of created
as False
. Or what?
Upvotes: 2
Views: 415
Reputation: 99640
Django's models gives a convenience method called get_or_create
, which looks up for an object based on specified criteria (in kwargs
). If the criteria do not match, a new object is created.
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 created_datetime
or similar field), hence the created
. It is a boolean variable, which is set to True
if a new object was created by the ORM, and set to False
if an existing object was retrieved.
Now, in your scenario:
obj, created = Person.objects.get_or_create(first_name=’John’, last_name=’Lennon’, defaults={’birthday’: date(1940, 10, 9)})
This is saying, get me the Person
object with first_name = John, last_name = Lennon, birthday = ...
If this is not found, create a new one for me.
The defaults
specify the initial value of the field birthday
while creating the object in this scenario.
This is also equivalent of writing
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')
In the signal's receiver, kwargs
is a dictionary with custom key-value pairs.
When you look at the signals' documentation, lets say post_save
has the following signature
django.db.models.signals.post_save
post_save(sender, instance, created, raw, using, update_fields)
This s the same as
post_save(sender, **kwargs) #where the rest of the args are a dictionary saved in **kwargs
Here, created
has a similar meaning. It is notifying the signal whether instance
was newly created, or updated.
So, if created = True
, new object was created. created=False
, object was probably updated.
Upvotes: 5
Reputation: 27855
created
is a boolean return variable of get_or_create(). If the object was created (SQL INSERT) with the get_or_create() call it is True
, if not (the object was fetched with SELECT) it is False
.
The second: MyModel.objects.create() forces a create (INSERT).
Upvotes: 0