Escolar Documentos
Profissional Documentos
Cultura Documentos
SIGN UP
Main menu
Articles Resources Downloads
Community
from django.
django.db
db import models
models
class Author
Author(
(models.
models.Model
Model)):
name = models.
models.CharField
CharField( (max_length
max_length==100
100)
)
def __str__
__str__(
(self
self)
):
return self
self.
.name
name
class Post
Post(
(models.
models.Model
Model)):
title = models.
models.CharField
CharField( (max_length
max_length=
=100
100))
content = models.
models.TextField
TextField( ()
published_date = models.
models.DateTimeField
DateTimeField((blank
blank=
=True
True,
, null
null=
=True
True)
)
author = models.
models.ManyToManyField
ManyToManyField( (Author
Author,, related_name
related_name=
="posts"
"posts"))
def __str__
__str__(
(self
self)
):
return self
self.
.title
Isso pode parecer um pouco assustador, então vamos acabar com isso. Temos dois
modelos: Autor e Post. Cada um tem um nome ou título. O post tem um grande campo
de texto para conteúdo e um para a data e hora de publicação. O Post também tem um ,
que une posts e autores.DateTimeFieldManyToManyField
A maioria dos tutoriais começa do zero — mas não é isso que vai acontecer na prática.
Na realidade, você vai receber um monte de código existente como o acima, e você tem
que descobrir o que tudo isso significa.model.py
Então agora é sua tarefa entrar no aplicativo e dar uma olhada ao redor. Há algumas
maneiras de fazer isso. Você pode fazer login no Django admin
(https://docs.djangoproject.com/en/1.11/ref/contrib/admin/), um backend baseado na Web
que tem todos os aplicativos listados e as maneiras de manipulá-los. Vamos voltar a
isso. aqui estamos interessados no ORM.
darwin
Type "help"
"help",
, "copyright"
"copyright",
, "credits" or "license" for more information.
information.
(InteractiveConsole
InteractiveConsole)
)
>>>
Isso nos levará a um console interativo. O comando shell
(https://docs.djangoproject.com/en/1.11/ref/django-admin/#shell) fez muita configuração
para nós, incluindo importar nossas configurações e configurar o ambiente Django.
Embora tenhamos lançado a concha, não podemos acessar nosso modelo de Blog até
que o importemos.
Isso importa todos os modelos de blog para que possamos brincar com nossos posts e
autores de blogs.
>>> Author.objects.all()
O que vamos obter deste comando é um de resultados, que lista todos os nossos
objetos Autor. Também não vamos encher todo o nosso console, porque se houver
muitos resultados, Django automaticamente truncará os resultados impressos.QuerySet
>>> Author.
Author.objects
objects.
.all
all(
()
>>> Author.
Author.objects
objects..get
get(
(name
name=
="VM (Vicky) Brasseur")
Brasseur")
<Author: VM (Vicky
Vicky)
) Brasseur
Brasseur>>
Desta vez, temos um único objeto com o que podemos interagir, em vez de uma lista.
Podemos interagir com este objeto pythonicamente, usando qualquer uma das colunas
de tabela como atributos para olhar para o objeto.QuerySet
>>> vmb = Author.
Author.objects
objects.
.get
get(
(name
name=
="VM (Vicky) Brasseur")
Brasseur")
>>> vmb.
vmb.name
name
And this is where the cool stuff happens. Normally in relational databases, if we want to
show information for other tables, we'd need to write a , or other table-coupling functions,
making sure that our foreign keys match up between tables. Django takes care of that for
us.LEFT JOIN
In our model, authors write many posts, so our Author object can check what posts the
author has made.
>>> vmb.
vmb.posts
posts..all
all(
()
QuerySet[
QuerySet [<Post: "7 tips for nailing your job interview">,
interview">,
<Post: "5 tips for getting the biggest bang for your cover letter buck">,
buck">,
... print
print(
(post.
post.title
title)
)
...
...
interview
5 tips for getting the biggest bang for your cover letter buck
buck
To do more complex querying, we can use filters instead of getting everything. Here is
where it gets tricky. In SQL, you have options such as , , and other filtering objects. You
can do all these things in the ORM, too, but it has a special way of doing them: by using
implicitly (rather than explicitly) defined functions.likecontains
If I call a function in my Python script, I'd expect somewhere there would be a matching .
This is an explicit functional definition. However, in the ORM, you can call a function that
isn't explicitly defined. Before, we were using to match on a name. But, if we wanted to do
a substring search, we can use .do_thing()def do_thingnamename__contains
>>> Author.
Author.objects
objects.
.filter
filter(
(name__contains
name__contains=
="Vic"
"Vic")
)
QuerySet[
QuerySet[<Author: VM (Vicky
Vicky)
) Brasseur
Brasseur>,
>, <Author: Victor Hugo">]
Hugo">]
Now, a small note about the double underscore (). These are very Python. You may have
seen or in your travels in Pythonland. These are sometimes referred to as , a shortening
of "double underscore." There are only a few non-alphanumeric characters that can be
used in object names in Python; underscore is one of them. These are used in the ORM
as an explicit separator of different parts of the filter key name. Under the hood, the string
is split by these underscores, and the tokens are processed separately. gets changed into
. In other programming languages, you may use arrows instead, such as in PHP. Don't let
dunders scare you, they're just pythonic helpers! (And if you squint, you could say they
look like little snakes, little pythons that want to help you with your
code.)____main____repr__dunder methodsname__containsattribute: name, filter: containsname->contain
The ORM is extremely powerful and very pythonic. But what about that Django admin site
I mentioned above?
One of the brilliant user-accessibility features of Django is its admin interface. If you
define your models, you get a nice web-based editing portal, for free.
If you'd like to know more, the Django Girls tutorial (https://djangogirls.org) section
about the ORM (https://tutorial.djangogirls.org/en/django_orm/) has a detailed
walkthrough. There's also copious documentation on the Django project website
(https://docs.djangoproject.com/en/1.11/topics/db/).
Topics :
Python (/tags/python) Web development (/tags/web-development)