Tutorial: Learning the DB-API and ORM

Posted: March 20th, 2010 | Author: | Filed under: Django, programming, Python | 58 Comments »

So far in the tutorial we’ve started our projectsetup the database, enabled the admin interfacecreated models for our blog. We’re going to slow down on actually developing our blog and talk about exactly how we get to the data we’ve stored in the database so far. The Admin Interface is great but, it doesn’t provide good programtic access to the data. Let’s open up a python shell but, we’re going to do it a special way when working with Django. From the command line in our root project directory (blog/)

$ python manage.py shell
Python 2.5 (r25:51918, Sep 19 2006, 08:49:13)
[GCC 4.0.1 (Apple Computer, Inc. build 5341)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
(InteractiveConsole)
>>>

Now this might look like a normal Python shell because, well it is. We’ve just loaded up some stuff in the background like path information to make our lives a bit easier. Now we have two models that we created in the application “main”. Let’s load those up in the shell.

>>> from main.models import Category
>>> from main.models import BlogPost

Before we get too deep here, I want to mention that everything that we do in the shell we can do in our application. It’s the same thing. So any manipulation we make here we can use the exact same code anywhere in our application. The shell is a great way to test out ideas and algorithms before we put that code into our application. We have our two models loaded up lets play with the built in “objects” Manager.

>>> BlogPost.objects.all()
[<BlogPost: Our First Post>]
>>> Category.objects.all()
[<Category: Books>]

For both of our models we are calling the function all() in the object manager. This will return a special Django object called a QuerySet. These are very powerful objects which we’ll see in a second. Let’s get all of the posts for a specific category.

>>> Category.objects.all()
[<Category: Books>]
>>> cat = Category.objects.all()[0]
>>> cat
<Category: Books>

Now even though objects.all() returns an object called a QuerySet it also works just like a standard array. So I’ve just taken the first element of the array “[0]” and assigned it to cat. So now we have a variable “cat” which contains one of our Categories called “Books”. We can see that the category has a Name which is called “Books”. Remember when we defined our __unicode__ object back in the create our models part. This is why python is calling our object . If we hadn’t defined the __unicode__ function python would print out our object like this:<Category: Category object>

Now that we have a specific category lets find all the blog posts associated with that category. I’m going to show you two different ways of doing this just show you two different new things.

>>> BlogPost.objects.filter(Category=cat)
[<BlogPost: Our First Post>]

>>> all_blog_posts = BlogPost.objects.all()
>>> all_blog_posts
[<BlogPost: Our First Post>]
>>> all_blog_posts.filter(Category=cat)
[<BlogPost: Our First Post>]

In the first line of code we are taking the same BlogPost.objects but, instead of calling all() we are calling filter. Filter is a function where we can compare any field from our model declaration in models.py and find only things that match that comparison. So here we are finding all the BlogPost that have a Category=cat (which is Category: Books).

The second example we are taking all the objects from BlogPost and putting them into all_blog_posts. Now this is a QuerySet object we mentioned before. It has the same methods as all of our model’s. So I can simple just filter that QuerySet for all of the posts that are in the Category : Books. The result of BOTH of those examples is still a QuerySet so I can filter them again, and again. There are a lot of functions in QuerySet’s that are very cool. We only touch on a very of them here. For a more in depth look goto our Quick Reference: QuerySets

So we’ve seen the basic ways to retrieve objects. Let’s create a new BlogPost from the shell.

>>> from django.contrib.auth.models import User
>>> User.objects.all()
[<User: DeGizmo>]
>>> degizmo = User.objects.all()[0]

>>> new_post = BlogPost()
>>> new_post.Title = "blog post from the shell"
>>> new_post.Category = cat
>>> new_post.Slug = "this-slug-shell"
>>> new_post.PostText = "this is the text of the blog post!"
>>> new_post.Author = degizmo
>>> new_post.save()
>>> BlogPost.objects.all()
[<BlogPost: Our First Post>, <BlogPost: blog post from the shell>]

The first thing we did was import the model “User” which we used before when we declared our model. Then I selected myself (the only user) and assigned it to the variable “adam”.

Now I created a new BlogPost object called new_post and went through each field in the model and assigned it a value. Then I called the function .save() which saves the new object to our database. Which you can see when we look at all of the objects stored in BlogPost. Go check the admin interface and you’ll see our new BlogPost right there along side of the rest of them.

Let’s say we want to change the title of that blog post for some reason (maybe we don’t like the capitalization).

>>> BlogPost.objects.all()
[<BlogPost: Our First Post>, <BlogPost: blog post from the shell>]
>>> BlogPost.objects.get(Title="blog post from the shell")
<BlogPost: blog post from the shell>

>>> edit = BlogPost.objects.get(Title="blog post from the shell")
>>> edit.Title = "Blog Post From The Shell!"
>>> edit.save()
>>> BlogPost.objects.all()
[<BlogPost: Our First Post>, <BlogPost: Blog Post From The Shell!>]

So once again we look at all of our BlogPost objects. This time I use a different function called get. This function doesn’t return a QuerySet but, just a single object from the database. It works the same way as filter, you tell it which field you want to compare in the database and it will return the right object. I just used the post title we want to change. Once I have stored the right post in the variable “edit” I edit the field “Title” then save it to back to the database with the function call save()

Maybe we don’t like that post at all anymore so let’s delete it.

>>> BlogPost.objects.all()
[<BlogPost: Our First Post>, <BlogPost: Blog Post From The Shell!>]
>>> edit = BlogPost.objects.get(Title="Blog Post From The Shell!")
>>> edit
<BlogPost: Blog Post From The Shell!>
>>> edit.delete()
>>> BlogPost.objects.all()
[<BlogPost: Our First Post>]

I got the BlogPost I wanted the same way as before using the “get” function, stored it in the variable edit. Then just called the function delete()

From the console we’ve returned all the categories, blog posts, posts just for a category, a single blog post, edited a blog post and deleted a blog post. Without writing a single line of SQL. Odds are you’ll almost never have to write a single line of SQL while working in Django unless you have some really complex models.

Now that we know how to get data out of the database let’s write our first view


58 Comments on “Tutorial: Learning the DB-API and ORM”

  1. 1 Enhatsnet said at 2:55 am on January 8th, 2011:

    Запомните их лица, потому что когданибудь вы скажете своим детям и внукам, что вы служили с такими мужчинами и женщинами, каких ещё не видела вселенная. Наверное, в туалет пошла. Вы стали для меня семьей! Это было тем летом, когда мы были свободны от правил. [url=http://xirothocpu.noadsfree.com]xirothocpu.noadsfree.com[/url] [url=http://zoxovderpe.noadsfree.com]zoxovderpe.noadsfree.com[/url] [url=http://xocebmovmu.noadsfree.com]xocebmovmu.noadsfree.com[/url] [url=http://midensigze.noadsfree.com]midensigze.noadsfree.com[/url] [url=http://todiggalya.noadsfree.com]todiggalya.noadsfree.com[/url]
    Я чувствую, что удача на его стороне. Так это я, значит, старое дело? Сильвия, прекрати, займемся этим в следующий раз. Как в индейской резервации. [url=http://qoqurvobpu.noadsfree.com]qoqurvobpu.noadsfree.com[/url] [url=http://duyunyeppe.noadsfree.com]duyunyeppe.noadsfree.com[/url] [url=http://jecejtadme.noadsfree.com]jecejtadme.noadsfree.com[/url] [url=http://sazettoyvu.noadsfree.com]sazettoyvu.noadsfree.com[/url] [url=http://huxepsince.noadsfree.com]huxepsince.noadsfree.com[/url]
    Не могу поверить, что ты оказалась достаточно тупой, прилетела сюда и застряла здесь изза шторма. Я уже купил билеты, и их уже не вернуть. Я думаю о самосохранении. [url=http://tuvinfecji.noadsfree.com]tuvinfecji.noadsfree.com[/url] [url=http://peqektapte.noadsfree.com]peqektapte.noadsfree.com[/url] [url=http://zadocyumwo.noadsfree.com]zadocyumwo.noadsfree.com[/url] [url=http://fuzesbalzo.noadsfree.com]fuzesbalzo.noadsfree.com[/url] [url=http://zipedjoyle.noadsfree.com]zipedjoyle.noadsfree.com[/url]

  2. 2 deafenmum said at 9:49 am on January 16th, 2011:

    Enter comment here.

  3. 3 Prappytarse said at 1:43 pm on January 18th, 2011:

    Enter comment here.

  4. 4 SmentSeavytaK said at 3:39 pm on January 18th, 2011:

    Enter comment here.

  5. 5 aKMoodeentert said at 10:07 pm on January 21st, 2011:

    Enter comment here.

  6. 6 exceshybuisse said at 5:10 am on January 27th, 2011:

    Enter comment here.

  7. 7 kubyduj said at 1:44 pm on January 27th, 2011:

    Enter comment here.

  8. 8 enteniThund said at 8:46 am on January 28th, 2011:

    Enter comment here.

  9. 9 HemyTyncknicy said at 5:39 pm on February 2nd, 2011:

    Enter comment here.

  10. 10 heceAroca said at 6:24 pm on February 3rd, 2011:

    Enter comment here.

  11. 11 romyTesyl said at 9:12 pm on February 23rd, 2011:

    Enter comment here.

  12. 12 Beenciemy said at 4:18 pm on February 26th, 2011:

    Enter comment here.

  13. 13 Voneembotam said at 9:54 pm on February 28th, 2011:

    Enter comment here.

  14. 14 Wanureaurrers said at 3:59 am on March 6th, 2011:

    Enter comment here.

  15. 15 Mitatotadearp said at 7:51 am on March 18th, 2011:

    Enter comment here.

  16. 16 Insanuado said at 6:50 am on March 20th, 2011:

    Enter comment here.

  17. 17 chorreoneycle said at 8:54 am on March 24th, 2011:

    Enter comment here.

  18. 18 aakolayre said at 2:47 pm on April 23rd, 2011:

    Enter comment here.

  19. 19 esomomofs said at 3:57 am on April 24th, 2011:

    Enter comment here.

  20. 20 Agislabbago said at 10:26 am on April 28th, 2011:

    Enter comment here.

  21. 21 aagerdonsa said at 7:15 am on May 8th, 2011:

    Enter comment here.

  22. 22 vuhAbsosybofs said at 6:30 am on May 10th, 2011:

    Enter comment here.

  23. 23 Headayovepe said at 12:26 pm on May 12th, 2011:

    Enter comment here.

  24. 24 Nigoidiotly said at 10:32 pm on May 17th, 2011:

    Enter comment here.

  25. 25 Uniontoum said at 7:34 am on May 18th, 2011:

    Enter comment here.

  26. 26 MolleyMyhon said at 3:20 pm on May 20th, 2011:

    Enter comment here.

  27. 27 Atticfuet said at 6:58 pm on May 21st, 2011:

    Enter comment here.

  28. 28 aasrebast said at 8:03 am on May 22nd, 2011:

    Enter comment here.

  29. 29 Geriapefm said at 8:02 pm on May 23rd, 2011:

    Enter comment here.

  30. 30 tgoanlaay said at 8:48 am on May 24th, 2011:

    Enter comment here.

  31. 31 HoockyAnymn said at 11:24 am on May 24th, 2011:

    Enter comment here.

  32. 32 AppellWex said at 5:32 am on May 26th, 2011:

    Enter comment here.

  33. 33 aakilops said at 5:03 am on June 2nd, 2011:

    Enter comment here.

  34. 34 Weiqueg said at 6:19 pm on June 7th, 2011:

    Enter comment here.

  35. 35 Tiximpait said at 8:29 am on June 13th, 2011:

    Enter comment here.

  36. 36 actuasiaw said at 8:07 pm on June 15th, 2011:

    Enter comment here.

  37. 37 bobsteam said at 3:19 pm on June 16th, 2011:

    Enter comment here.

  38. 38 Fritteeda said at 12:56 pm on June 18th, 2011:

    Enter comment here.

  39. 39 Dertabrarse said at 8:26 am on June 22nd, 2011:

    Enter comment here.

  40. 40 illuttaquandy said at 6:45 am on June 26th, 2011:

    Enter comment here.

  41. 41 NomshomyTum said at 7:48 am on June 28th, 2011:

    Enter comment here.

  42. 42 Opinsnawswone said at 5:42 am on June 29th, 2011:

    Enter comment here.

  43. 43 alenarule said at 11:59 am on July 4th, 2011:

    Enter comment here.

  44. 44 AntoreyDenKab said at 2:52 am on July 5th, 2011:

    Enter comment here.

  45. 45 envereown said at 3:31 am on July 9th, 2011:

    Enter comment here.

  46. 46 Wepphedgest said at 12:29 pm on July 15th, 2011:

    Enter comment here.

  47. 47 nityadank said at 2:59 am on July 18th, 2011:

    Enter comment here.

  48. 48 nityadankx654424 said at 10:09 am on July 23rd, 2011:

    Enter comment here.

  49. 49 serretaninna said at 10:35 pm on July 28th, 2011:

    Enter comment here.

  50. 50 Effiggime said at 9:34 pm on July 30th, 2011:

    Enter comment here.

  51. 51 Embeskbeata said at 1:20 am on July 31st, 2011:

    Enter comment here.

  52. 52 averaregu said at 12:01 am on August 1st, 2011:

    Enter comment here.

  53. 53 GoroNofsSox said at 12:50 pm on August 5th, 2011:

    Enter comment here.

  54. 54 lorEndalaralm1995 said at 11:50 am on August 12th, 2011:

    Enter comment here.

  55. 55 grusla said at 5:50 am on August 13th, 2011:

    Enter comment here.

  56. 56 LarryMRubio said at 2:48 am on August 14th, 2011:

    Enter comment here.

  57. 57 Kipiyanka said at 1:56 pm on August 16th, 2011:

    Enter comment here.

  58. 58 smerynime said at 7:28 pm on August 24th, 2011:

    Enter comment here.


Leave a Reply