There are different methods which we can use to get, create and update the django models. You can learn more about this in great detail from django documentation. This is more of summarization of methods which I usually use
while developing models in django.

Let’s jump into the code without going much into details:

We have model called Author with following information in django:

 class Author(models.Model):
    uuid = models.CharField(max_length=32, blank=True, null=True)
    first_name = models.CharField(length=20)
    last_name = models.CharField(length=20)
    salary = models.IntegerField(default=0)
    has_published = models.BooleanField(default=False)

Now we want to get the information of the user, You could use one of these method:
Using get() method
get gives you one result or will raise an exception if not found the record

try:
    get_user = User.get(first_name='abcd', last_name='xyzw',
                        uuid='83ef72b7-bd3b-4dbf-bac1-4928cad32183')
except Author.DoesNotExist:
    raise HttpException(404, 'The requested object(s) could not be found.')

Using filter() method
filter gives you list of objects, if not record found it give you empty list

get_user = User.filter(first_name='abcd', last_name='xyzw',
                       uuid='83ef72b7-bd3b-4dbf-bac1-4928cad32183')
if get_user.exist():
    print 'record exist'
else:
    print 'record does not exist' 

 
get_or_create
Apart from getting the data from model, sometime it’s necessary to perform actions like create or update after get, so django provide use two methods which fulfill this gap:
If you would like to do following steps then use get_or_create method:

  • Get the record
  • If found: get the record
  • If not found: create the record

This handle DoesNotExist exception for you, so you don’t need to put on try/except block.
get_or_create method helps to do that:

 
obj, created = get_or_create(first_name='abcd', last_name='xyzw', 
                uuid='83ef72b7-bd3b-4dbf-bac1-4928cad32183') 
if obj: 
     # record already exist 
if created: 
     # Created new record 

 
update_or_create
If you would like to do following steps where you want to update or create the record. It would be easier to use the udpate_or_create method.
The steps involved in method as this:

  • Get the record
  • If found: Update the record
  • If not found: Create new record

This handle DoesNotExist exception for you, so you don’t need to put on try/except block.
Above steps can be performed using update_or_create method:

defaults = {'first_name': 'pqrst'}
obj, created = update_or_create(first_name='abcd', last_name='xyzw',
                             uuid='83ef72b7-bd3b-4dbf-bac1-4928cad32183',
                             defaults = {'first_name': 'pqrst'})
if obj:
   # record already exist
if created:
   # update record with defaults 

Hope this helps you to learn some of common method to get, create, update from django model.

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

Blog at WordPress.com.

Up ↑

%d bloggers like this: