0% found this document useful (0 votes)
5 views12 pages

Models

Uploaded by

malikrejoice87
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
5 views12 pages

Models

Uploaded by

malikrejoice87
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 12

QSpiders Global

PYTHON FULL STACK


INSTRUCTOR: RAJAT NAROJI
SUBJECT: DJANGO-FRAMEWORK

DJANGO MODELS

Introduction to Django Models


- In Django, models are used to define the structure of your database.
Each model corresponds to a single database table, and each attribute of
the model represents a database field.
- Django models let you work with your database using Python code
instead of writing complex SQL queries.
- Models are defined as classes in Django and are subclasses of
django.db.models.Model.

Defining a Model
- To define a model in Django, you create a class that inherits from
django.db.models.Model. Each attribute of the class represents a
database field.
- Example:

- First we have the import statement which imports the django models module.
- Secondly we start with the model definition along with the fields.
Django models Fields:
Django provides various field types that you can use to define your model's
attributes: Basically These Fields specify what type of data to be accepted from
the User.
- CharField: Used for short text fields. Requires a max_length
parameter to specify the maximum length.
-Ex: name = models.CharField()

- TextField: Used for large text fields.


Ex: bio= models.TextField()

- BooleanField: Used for True/False values.


- Ex: completed = models.BooleanField()

- DateField: Used for Date.


- Ex: birth_date = models.DateField()

- DateTimeField: Used for date and time. You can use auto_now_add
to set the field to the current date and time when the object is created,
and auto_now to update it each time the object is saved.
- Ex: created_at = models.DateTimeField(auto_now_add=True)

- TimeField: Used for Integer values.


- Ex: start_time = models.TimeField()

- IntegerField: Used for Integer values.


- Ex: age = models.IntegerField()

- FloatField: Used for floating-point numbers.


- Ex: price = models.FloatField()

- EmailField: Used for email addresses.


- Ex: email = models.EmailField()
- URLField: Used for URLs.
- Ex: website = models.URLField()
-
- FileField: Used for Uploading files.
- Ex: file = models.CharField(upload_to='uploads/')

- ImageField: Used for Uploading Images.


- Ex: profile_pic = models.ImageField(upload_to=’images/’)
• ImageField() uses a python library called Pillow so if
we are using this field we might have to run pip
install Pillow before running any migrations.
- SlugField: Used for URL-friendly text, typically for unique identifiers.
• Ex: slug = models.SlugField(unique=True)

- AutoField: An integer field that automatically increments,


usually used as a primary key.
• Ex: id = models.AutoField(primary_key=True)

- ForeignKey: Defines a many-to-one relationship.


• Ex: author = models.ForeignKey(User,
on_delete=models.CASCADE)

- ManyToManyField: Defines a many-to-many relationship.


- Ex: tags = models.ManyToManyField(Tag)

- OneToOneField: Defines a one-to-one relationship.


- Ex: profile = models.OneToOneField(Profile, on_delete=models.CASCADE)

After creating or modifying a model in Django, the next important step is to create
and apply migrations. Migrations are Django's way of propagating changes which
you make to your models (like adding a field or deleting a model) into your
database schema
What are Migrations?

Migrations are files that Django generates to keep track of changes in your models and
apply those changes to your database schema. They allow you to update your database
structure without losing data.

Why Use Migrations?

● Version Control: Migrations help in tracking changes to the database schema


over time.
● Easy Deployment: Migrations allow you to propagate model changes to different
environments (development, staging, production) in a consistent way.
● Database Consistency: They help maintain the structure of the database
in sync with the models in your code.

Workflow for Migrations

1. Make Migrations
○ After creating or modifying a model, you need to generate a migration file.
This file records the changes you made to the model.
○ Command:

○ This command will scan your models and create a migration file in the
migrations directory of your app (Basically it converts python code to
sql query). The file will contain the instructions to apply the changes you
made to your models.
1. Apply Migrations

○ After generating the migration file, you need to apply it to your


database. This step updates the database schema according to the
instructions in the migration file.
○ Command:
○ This command reads the migration files and applies the changes to the
database. If this is the first time you run a migration, Django will create
the necessary database tables for the models you have defined.

Migration Files

Migration files are automatically created in the migrations directory of your app.
They are named with a timestamp and a brief description of the change, like
0001_initial.py for the first migration or 0002_add_due_date.py if you added a
field, etc..

Migration Commands

● makemigrations: Generates new migration files based on the


changes detected in models.
● migrate: Applies the generated migrations to the database, updating
its schema.
● showmigrations: Lists all migrations and their status (whether they have been
applied or not).
● sqlmigrate: Shows the SQL statements for a specific migration. Useful
for understanding what Django is doing to the database.

Admin Panel in Django

The Django admin panel is a powerful built-in interface that allows you to manage your
application's data without having to write custom code for basic CRUD (Create, Read,
Update, Delete) operations.
How to set up and use the Django admin panel:

1. Creating a Superuser

To access the Django admin panel, you need to create a superuser. A superuser has all
permissions in the Django admin interface, including the ability to add, edit, delete, and
view all data.

Steps:

● After running the command, you'll be prompted to enter a username,


email address, and password.
● Once you’ve entered the information, Django will create a superuser account.

2. Logging in to the Admin Page

● Accessing the Admin Page:


○ Start the Django development server.
○ Open your web browser and go to http://127.0.0.1:8000/admin/
● Logging in:
○ Use the superuser credentials you created (username and password)
to log in to the admin interface.
○ Upon successful login, you'll be redirected to the admin dashboard.

3. Registering Models in the Admin Panel

By default, the Django admin panel does not automatically display your models. You
need to explicitly register each model you want to manage through the admin interface.
● Registering a Model:
○ Open admin.py in your app's directory.
○ Import the model you want to register.
○ Use the admin.site.register() function to register your model.

4. CRUD Operations Using the Admin Panel

Once your model is registered, you can perform CRUD operations (Create, Read,
Update, Delete) directly through the admin interface.

CRUD Operations in Django


CRUD stands for Create, Read, Update, and Delete. These are the four basic
operations you can perform on data in a database. Here's how you can implement
CRUD operations in Django using views, forms, and the Django shell.

1. Understanding CRUD Operations Using Django Shell

The Django shell allows you to interact with your Django project's models and database
directly from the command line. It's useful for testing queries, creating objects, and
debugging.

● Accessing the Django Shell:


● Create:

● Read:
○ all() method:

○ get() method:

○ filter() method:
● Update:

● Delete:

2. Implementing CRUD Operations in Views

You can implement CRUD operations in Django views by defining functions that handle
different HTTP methods like GET and POST.

● Create (via POST Request):


● Read (via GET Request):

● Update (via POST Request):

● Delete (via POST Request):


3. Passing GET/POST Requests Through Forms :

Django uses HTML forms to pass GET and POST requests. Here’s how you can create
simple forms for each operation.

● Form Template for Updating a Task (update_task.html):

● Form Template for Updating a Task (update_task.html):


Redirecting After a Form Submission

After successfully handling a form submission, it's a good practice to redirect the user to
another page, such as a list view or a success page.

● Using the redirect() Function:

Redirects: The redirect() function is used to send an HTTP redirect to the user,
taking them to a different view or URL after an operation is completed.

You might also like