SHELL – DATA BASE sqlite3
From cmd:
python [Link] shell
class Book([Link]):
title = [Link](max_length=50)
rating = [Link]()
[Link]
table: book_outlet_book
TO APPEND OR CREATE:
from book_outlet.models import Book # to use Book
HP=Book(title="Harry Potter 1", rating=3) # creo una instancia de Book
[Link]() # ahi esta añadido en la BD
# ----- another way quicker and don’t need save()
<Book: titulo=El marino, rating=3>
TO GET:
[Link]()
<QuerySet [<Book: Book object (1)>, <Book: Book object (2)>]>
# un poco confuse pero al añadir __st__ method en el modelo Book, tengo:
def __str__(self):
return f"titulo={[Link]}, rating={[Link]}"
[Link]() # debo salir (exit() )y entrar de nuevo al shell
<QuerySet [<Book: titulo=Harry Potter 1, rating=9>, <Book: titulo=Lord of the Rings, rating=7>]>
class Book([Link]):
title = [Link](max_length=50)
rating = [Link](validators=[MinLengthValidator(1), MaxLengthValidator(5)])
author = [Link](null=True, max_length=100)
is_bestselling = [Link](default=False)
[Link]()[1] # to get the second book
<Book: titulo=Lord of the Rings, rating=7>
HP= [Link]()[0]
[Link]
Harry Potter
[Link]()[1].title # to access any field
‘Lord of the Rings’
TO UPDATE:
HP=[Link]()[0]
[Link]=”Willian Potter”
[Link]() # ojo NO: [Link]()
# IF RECORD EXISTS ONLY UPDATES IF NEW CREATES
TO DELETE:
HP=[Link]()[0]
[Link]() # deletes without warning
(1, {‘book_outlet.Book’: 1})
TO QUERY 1 OBJECT ONLY – get(): # If there are more obj then raise error
[Link](id=2)
<Book: titulo=Lord of the Rings, rating=2>
[Link](is_bestselling=True)
Error !
TO QUERY 1 or more OBJECTS – filter():
[Link] - bulk-update
QuerySet API reference
__iexact= (i is ignore case)
__exact=
=
__lt=
__lte=
__gt=
__gte=
__eq=
[Link](is_bestselling=True)
<QuerySet [<Book: titulo=Sirenita, rating=3>, <Book: titulo=Popeye el marino, rating=5>, <Book: titulo=Light Gear,
rating=3>]>
From [Link] import Q # useful
| = or
, = and
[Link](Q(id=4) | Q(author="Pixar"))
<QuerySet [<Book: titulo=Sirenita, rating=3>, <Book: titulo=Piratas 1, rating=2>, <Book: titulo=Light Gear, rating=3>]>
[Link](Q(id__lt=8),Q(author="Pixar"))
<QuerySet [<Book: titulo=Piratas 1, rating=2>, <Book: titulo=Light Gear, rating=3>]>
[Link](is_bestselling=True) # exclude() is opposite to filter()
<QuerySet [<Book: titulo=Lord of the Rings, rating=2>, <Book: titulo=El marino, rating=3>, <Book: titulo=Piratas 1,
rating=2>]>
[Link](is_bestselling=True).exclude(id__gt=4) # can combine filter() and exclude()
<QuerySet [<Book: titulo=Sirenita, rating=3>]>
[Link]().exclude(id__lt=3).filter(author=‘Pixar’)
<QuerySet [<Book: titulo=Piratas 1, rating=2>, <Book: titulo=Light Gear, rating=3>]>
Slicing operator
[Link]()[1:2]
<QuerySet [<Book: titulo=El marino, rating=3>]>
[Link]()[0:3:2]
[<Book: titulo=Lord of the Rings, rating=2>, <Book: titulo=Sirenita, rating=3>]
Sorting
[Link].order_by(‘author’) # single quotes
<QuerySet [<Book: titulo=Lord of the Rings, rating=2>, <Book: titulo=Piratas 1, rating=2>, <Book: titulo=Light Gear,
rating=3>, <Book: titulo=El marino, rating=3>, <Book: titulo=Popeye el marino, rating=5>, <Book: titulo=Sirenita,
rating=3>]>
[Link].order_by(‘-author’)
<QuerySet [<Book: titulo=Sirenita, rating=3>, <Book: titulo=El marino, rating=3>, <Book: titulo=Popeye el marino,
rating=5>, <Book: titulo=Piratas 1, rating=2>, <Book: titulo=Light Gear, rating=3>, <Book: titulo=Lord of the Rings,
rating=2>]>
[Link].order_by(‘-author’, ‘id’)
<QuerySet [<Book: titulo=Sirenita, rating=3>, <Book: titulo=El marino, rating=3>, <Book: titulo=Popeye el marino,
rating=5>, <Book: titulo=Piratas 1, rating=2>, <Book: titulo=Light Gear, rating=3>, <Book: titulo=Lord of the Rings,
rating=2>]>
Chain Queries # can mix filter and exclude
[Link](is_bestselling=True).filter(author="Pixar").filter(id__gt=1)
<QuerySet [<Book: titulo=Piratas 1, rating=2>]>
Save()
[Link](id=3).save() # especalmente si quiero actualizer algo en la bd como slug
ABC= [Link](id=3)
[Link]=”El Marinero 1”
[Link]()
Aggregate()
books = [Link]().order_by("title")
avg = [Link](Avg("rating"), Min("rating"), Max("rating"))
Working with 2 or more Models:
from book_outlet.models import Book, Author
si ya tenia un autor en id=6
A6= [Link](id=6)
[Link](title="La Selva", author=A6, rating=4, is_bestselling=True)
---
A2=[Link](first_name="Angel", last_name="Alarcon")
A1=[Link](first_name="Waltz", last_name="Disney")
B1=[Link](title="El Marino", author=A1, rating=3, is_bestselling=False)
B1=[Link](title="Avengers 1", author=A2, rating=3, is_bestselling=False)
B2=[Link](title="La Sirenita", author=A2, rating=3, is_bestselling=False)
B2=[Link](title="La Selva", author=A1, rating=4, is_bestselling=True)
---
Elmarino = [Link](title="El Marino")
>>> [Link] # ahora puedo ver de Author sin problema
<Author: Author object (7)>
>>> [Link].first_name # y los campos de Author tambien
'Waltz 2'
>>> [Link].last_name
'Disney 2'
---
Queries from Book:
book_from_eistein=[Link](author__last_name="Einstein")
book_from_eistein
<QuerySet [<Book: El Marino 5(4)>, <Book: El Laberinto(5)>]>
>>>
book_from_eistein=[Link](author__last_name__contains="tein")
<QuerySet [<Book: El Marino 5(4)>, <Book: El Laberinto(5)>]>
Queries from Author book_set (default). Se puede cambiar: (reverse query)
Esta cambiado a "bookrel" for onetomany relationship
A=[Link](first_name="Juan") # because is one to many
<QuerySet [<Author: Author object (2)>]>
>>> [Link]
<[Link].related_descriptors.create_reverse_many_to_one_manager.<locals>.RelatedManager
object at 0x00000254ABF761D0>
THE ONE TO ONE RALTIONSHIP IT IS NOT NECESSARY, ONLY THE NAME OF THE CLASS IN LOWERCASE:
A1=[Link](street="Av Interoceanica", postal_code="45", city="Cuenca")
Au=[Link](first_name="Juan") # because is one to one
>>> [Link]
>>> [Link]=A1 # to assign in one to one or many to one
MANY TO MANY RELATIONSHIP
C1=[Link](name="Germany", code="GE")
B1=[Link](id=3)
>>> B1.published_countries = C1 # for many to many does not work
>>> B1.published_countries.add(C1) # use this way
>>> [Link]()
For inverse:
Create a SuperUser [Link]:8000/admin
In the Shell:
python [Link] createsuperuser
Al final :
runserver
Username (leave blank to use ‘angel2021’):
Email address: aeas2000@[Link]
Password:
Password (again):
This password is too short. It must contain at least 8 characters.
This password is too common.
This password is entirely numeric.
Bypass password validation and create user anyway? [y/N]: y
Superuser created successfully.
[Link] ( must be used when server is running)
book store:
Username (leave blank to use ‘angel’):
Email address: angel@[Link]
Password:123
Password (again):123
This password is too short. It must contain at least 8 characters.
This password is too common.
This password is entirely numeric.
Bypass password validation and create user anyway? [y/N]: y
Superuser created successfully.
[Link] ( must be used when server is running)
To start using en [Link]:
from book_outlet.models import Book # lo mismo que hago en shell
#from . models import Book
# Register your models here.
[Link](Book)
----------------------useful
python [Link] shell
from book_outlet.models import Book, Author, Address , Country
from [Link] import Review
python [Link] makemigrations
python [Link] migrate