¿Te pierdes entre tantos temas? 📚✨ Descubre todo lo que ofrece este blog en un solo vistazo [👉 Ver índice completo]
Se supone que ya sabes que es una base de datos, tablas, registros etc
Para ver este tema vamos a simular que creamos una tienda virtual. Empezaremos un nuevo proyecto independiente del que ya teníamos. Tecleamos:
$ django-admin startproject tiendaVirtual$ cd tiendaVirtualtiendaVirtual$ python manage.py startapp gestionPedidosmodels.py: Creación de tablas y campos.
from django.db import models
# Create your models here.
# Las tablas se crean mediante clases.
class Clientes(models.Model):
# Dentro de la clase se crean los diferentes campos.
nombre = models.CharField(max_length=30)
direccion = models.CharField(max_length=50)
# Email ya valido ya esta creado
email = models.EmailField()
telefono = models.CharField(max_length=9)
class Articulos(models.Model):
nombre = models.CharField(max_length=30)
categoria = models.CharField(max_length=20)
precio = models.IntegerField()
class Pedidos(models.Model):
numero = models.IntegerField
fecha = models.DateField()
entregado = models.BooleanField()METADATOS.
models.py: Creación de tablas y campos.
from django.db import models
# Create your models here.
# Las tablas se crean mediante clases.
class Clientes(models.Model):
# Dentro de la clase se crean los diferentes campos.
nombre = models.CharField(max_length=30)
direccion = models.CharField(max_length=50)
# Email ya valido ya esta creado
email = models.EmailField()
telefono = models.CharField(max_length=9)
class Meta:
ordering = ["nombre"]
...models.py: Creación de tablas y campos.
from django.db import models
# Create your models here.
# Las tablas se crean mediante clases.
...
class Pedidos(models.Model):
numero = models.IntegerField
fecha = models.DateField()
entregado = models.BooleanField()
class Meta:
indexes = [models.Index(fields=["numero"]),]
tiendaVirtual/settings.py: Registro de aplicaciones.
...
ALLOWED_HOSTS = []
# Application definition
INSTALLED_APPS = [
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'gestionPedidos',
]
MIDDLEWARE = [
.../DJANGO/tiendaVirtual$ python manage.py check gestionPedidos
System check identified no issues (0 silenced).
python manage.py makemigrations nombre_aplicación/tiendaVirtual$ python manage.py makemigrations gestionPedidos
Migrations for 'gestionPedidos':
gestionPedidos/migrations/0001_initial.py
- Create model Articulos
- Create model Clientes
- Create model Pedidos/tiendaVirtual$ python manage.py sqlmigrate gestionPedidos 0001
BEGIN;
--
-- Create model Articulos
--
CREATE TABLE "gestionPedidos_articulos" ("id" integer NOT NULL PRIMARY KEY AUTOINCREMENT, "nombre" varchar(30) NOT NULL, "categoria" varchar(20) NOT NULL, "precio" integer NOT NULL);
--
-- Create model Clientes
--
CREATE TABLE "gestionPedidos_clientes" ("id" integer NOT NULL PRIMARY KEY AUTOINCREMENT, "nombre" varchar(30) NOT NULL, "direccion" varchar(50) NOT NULL, "email" varchar(254) NOT NULL, "telefono" varchar(9) NOT NULL);
--
-- Create model Pedidos
--
CREATE TABLE "gestionPedidos_pedidos" ("id" integer NOT NULL PRIMARY KEY AUTOINCREMENT, "fecha" date NOT NULL, "entregado" bool NOT NULL);
COMMIT;/tiendaVirtual$ python manage.py migrate
Operations to perform:
Apply all migrations: admin, auth, contenttypes, gestionPedidos, sessions
Running migrations:
Applying contenttypes.0001_initial... OK
Applying auth.0001_initial... OK
Applying admin.0001_initial... OK
Applying admin.0002_logentry_remove_auto_add... OK
Applying admin.0003_logentry_add_action_flag_choices... OK
Applying contenttypes.0002_remove_content_type_name... OK
Applying auth.0002_alter_permission_name_max_length... OK
Applying auth.0003_alter_user_email_max_length... OK
Applying auth.0004_alter_user_username_opts... OK
Applying auth.0005_alter_user_last_login_null... OK
Applying auth.0006_require_contenttypes_0002... OK
Applying auth.0007_alter_validators_add_error_messages... OK
Applying auth.0008_alter_user_username_max_length... OK
Applying auth.0009_alter_user_last_name_max_length... OK
Applying auth.0010_alter_group_name_max_length... OK
Applying auth.0011_update_proxy_permissions... OK
Applying auth.0012_alter_user_first_name_max_length... OK
Applying gestionPedidos.0001_initial... OK
Applying sessions.0001_initial... OK¿Cómo crear, actualizar y borrar registros de la base de datos?
~/Cursos/DJANGO/tiendaVirtual$ python manage.py shell
Python 3.10.6 (main, Nov 14 2022, 16:10:14) [GCC 11.3.0] on linux
Type "help", "copyright", "credits" or "license" for more information.
(InteractiveConsole)
>>> ~/Cursos/DJANGO/tiendaVirtual$ python manage.py shell
Python 3.10.6 (main, Nov 14 2022, 16:10:14) [GCC 11.3.0] on linux
Type "help", "copyright", "credits" or "license" for more information.
(InteractiveConsole)
>>> from gestionPedidos.models import Articulos~/Cursos/DJANGO/tiendaVirtual$ python manage.py shell
Python 3.10.6 (main, Nov 14 2022, 16:10:14) [GCC 11.3.0] on linux
Type "help", "copyright", "credits" or "license" for more information.
(InteractiveConsole)
>>> from gestionPedidos.models import Articulos
>>> juego=Articulos(nombre="Doom", categoria="Acción", precio= 3)
~/Cursos/DJANGO/tiendaVirtual$ python manage.py shell
Python 3.10.6 (main, Nov 14 2022, 16:10:14) [GCC 11.3.0] on linux
Type "help", "copyright", "credits" or "license" for more information.
(InteractiveConsole)
>>> from gestionPedidos.models import Articulos
>>> juego=Articulos(nombre="Doom", categoria="Acción", precio= 3)
>>> juego.save()>>> juego2=Articulos(nombre="Need for Speed", categoria="Velocidad", precio=50)
>>> juego2.save()
>>> >>> juego3=Articulos.objects.create(nombre="Animal Crossing",categoria="Simulación", precio=45)>>> juego2.precio=60
>>> juego2.save()
>>>>>> borrar = Articulos.objects.get(id=3)
>>> borrar.delete()
(1, {'gestionPedidos.Articulos': 1})
>>>
>>> lista_articulos = Articulos.objects.all()
>>> lista_articulos
<QuerySet [<Articulos: Articulos object (1)>, <Articulos: Articulos object (2)>]>
>>> >>> lista_articulos.query.__str__()
'SELECT "gestionPedidos_articulos"."id", "gestionPedidos_articulos"."nombre", "gestionPedidos_articulos"."categoria", "gestionPedidos_articulos"."precio" FROM "gestionPedidos_articulos"'
>>> 








