Curso Django. BBDD II. Vídeo 12
Creating a Django Project: Tienda Online
Introduction to the Course
- The course focuses on Django and database management, building upon previous lessons about project structure.
- The current project is named "tienda online," which will include an application for managing clients, articles, and orders.
Setting Up the Project
- The instructor is working within a directory called "código proyectos cursos" specifically for Django courses.
- To create a new project, navigate to the console in Visual Studio Code and use the command
django-admin startproject tienda_online.
Creating the Application
- After creating the project, a new folder structure appears with essential files like
manage.py.
- To create an application named "gestión pedidos," navigate into the "tienda online" directory and run
python manage.py startapp gestión_pedidos.
Understanding Applications in Django
- A new directory for "gestión pedidos" is created; this corresponds to the first application within the project.
- It's clarified that while not every simple Python project requires an application, using Django typically implies some complexity necessitating modular applications.
Application Structure Overview
- The newly created application includes several files:
admin.py,apps.py,models.py, andviews.py—each serving specific functions in managing databases and views.
- The instructor emphasizes that these components are crucial for developing functionalities within the application.
Preparing for Database Management
- Moving forward, there will be a focus on setting up a database (initially of type SQLite), which will be located alongside
manage.py.
Creating a Database Structure in Django
Project Setup and Initial Steps
- The project involves setting up an online store, focusing on the order management section where existing files like settings and URLs are located.
- The models file is initially empty except for an import line, indicating that the approach will be object-oriented for database handling.
- Django automates SQL code generation, eliminating the need to manually write SQL commands such as
CREATE TABLE, which simplifies database management.
Understanding Models in Django
- Familiarity with SQL is beneficial when using frameworks like Django, although it’s possible to work without it. Knowledge of data access languages enhances development efficiency.
- A class named "Clientes" (Clients) will be created to represent the clients table in the database, utilizing
models.Modelfor functionality.
Defining Fields in Models
- The first field defined is "nombre" (name), specifying its type as a character field with a maximum length of 30 characters.
- For integer fields,
models.IntegerField()can be used; however, text storage requires character fields (models.CharField()).
Additional Field Specifications
- Other fields include "dirección" (address), also a text field but with a maximum length of 50 characters.
- An email field is created using
models.EmailField(), ensuring only valid email formats can be entered by requiring an '@' symbol and a period.
Completing Client Model Definition
- A phone number field is added as a character field limited to 7 characters since no specific template exists for phone numbers.
Defining Additional Tables: Articles and Orders
Creating Article Table
- The next model represents articles with similar parameters; it includes fields like "nombre" (name), set to hold up to 30 characters.
Price Field Implementation
- A price field is introduced as an integer type using
models.IntegerField(), which does not require additional parameters.
Order Table Structure
- The final model represents orders, including fields such as "número" (number), which uses
models.IntegerField().
Date and Delivery Status Fields
- A date field utilizes
models.DateTimeField()for capturing order dates accurately.
- An 'entregado' (delivered) status is implemented using
models.BooleanField(), allowing tracking of whether an order has been delivered or not.
Finalizing the Application Setup
Saving Changes and Next Steps
- After defining all necessary models representing three tables—clients, articles, and orders—the changes are saved.
Registering Applications in Django
Steps to Register Applications
- To register an application in a Django project, navigate to the
settings.pyfile located in the root directory of your project. In the "INSTALLED_APPS" list, add your newly created application (e.g., "gestión de pedidos") followed by a comma.
- After adding the application name, save the changes. This step is crucial for ensuring that Django recognizes and includes your new app within its framework.
Checking Application Status
- To verify if everything is functioning correctly, use the command
python manage.py check <app_name>in the console. Replace<app_name>with your application's name (e.g., "gestión pedidos"). If successful, it should indicate no issues.
- If errors are reported after running this command, you need to identify and correct them. Common issues may include syntax errors or mistakes in model definitions.
Creating and Migrating Database
- The database must be created using the command
python manage.py makemigrations. This will generate migration files for your application based on defined models.
- Upon successful execution of this command, you should see confirmation that migrations have been created for your app (e.g., "gestión de pedidos"). It will also specify which models were generated (e.g., articles, clients).
Viewing Database Structure
- After creating migrations, you can view the database structure using a tool like DB Browser for SQLite. Initially, you'll find that while the database exists, it contains no tables until migrations are applied.
- To populate this empty database with tables corresponding to your models, run
python manage.py migrate. This command applies all pending migrations and creates necessary tables within your database.
Generating SQL Code
- You can generate SQL code for specific migrations using
python manage.py sqlmigrate <app_name> <migration_number>, where<migration_number>corresponds to what was generated earlier (e.g., 0001).
- This process helps track changes over time; if modifications are needed later on, subsequent migration numbers will be assigned sequentially (e.g., 0002).
Finalizing Database Setup
- Once you've executed all commands successfully and migrated data into your database, you can confirm that it now contains multiple tables—some automatically created by Django essential for its operation alongside those you've defined.
Primary Key Management in Django
Understanding Primary Keys
- In Django, you can overwrite the default primary key by creating your own field. If not specified, Django automatically assigns a primary key.
- This automatic assignment is similar to how Microsoft Access handles primary keys when creating tables.
SQL Code Generation
- One of the advantages of using Django is that it generates SQL code tailored for the specific database management system (DBMS) being used.
- Different DBMS have subtle differences in their SQL implementations; thus, having appropriate SQL code ensures compatibility and functionality.
Conclusion and Resources
- The video concludes with an invitation to register for free courses on a virtual academy platform, where various topics are categorized for easier access.