21.01.2015 Views

color version - PET: Python Entre Todos - Python Argentina

color version - PET: Python Entre Todos - Python Argentina

color version - PET: Python Entre Todos - Python Argentina

SHOW MORE
SHOW LESS

Create successful ePaper yourself

Turn your PDF publications into a flip-book with our unique Google optimized e-Paper software.

The Django package includes:<br />

For example, if we want to get all users that are 20 years old, it could be dome through<br />

some code like this:<br />

past_teens = User.objects.filter(age = 20)<br />

[while we are at it: Django’s built-in authentication application already includes a User<br />

class that we can take advantage of :)]<br />

The first tool Django provides is an “Object Relational Mapper” (ORM). The ORM will<br />

allow us to interact with the database so it will be one of the two things that we will<br />

commonly use the most (so pay attention, this is like something that will be in the final<br />

for sure).<br />

Like we are using object-oriented programming, we are going to define and use classes.<br />

Like most commonly used databases are relational databases, Django will take care of<br />

translating our operations on objects into SQL statements that will run on the databases’<br />

tables.<br />

For example: we define our class User with several properties (name, address, email,<br />

etc.). We can then do things like create instances of User, store values in its properties<br />

and tell it: “hey, you, save yourself!”, Django will automagically create the appropriate<br />

update or insert SQL statement and run it in the database.<br />

The code for this example could look like this:<br />

new_user = User()<br />

new_user.name = 'Fisa'<br />

new_user.email = 'fisadev@gmail.com'<br />

new_user.address = 'somewhere in <strong>Argentina</strong>'<br />

new_user.save()<br />

We can now write code that reads from and stores stuff into the database, but that is not<br />

of much use to the user. We have to show him something. The second toll we’re going to<br />

use is the templates system.<br />

What’s that It is what will let us “inject” our data into HTML (or XML, or whatever)<br />

templates that we define.<br />

That is to say that we’ll build the HTML for the user to see in their browser but we’ll say<br />

within the file things like “here goes the name of the current user”.<br />

The template language also provides some basic logic structures that we can use like<br />

loops, conditionals and even some kind of template inheritance.<br />

Just like this, the ORM allows also us to read from the database, filter, run complex<br />

queries, etc.

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!