0% found this document useful (0 votes)
25 views9 pages

Django

Uploaded by

sid.bakshi2
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)
25 views9 pages

Django

Uploaded by

sid.bakshi2
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/ 9

In Django, particularly when using Django REST Framework (DRF), a serializer is a component

that allows you to convert complex data types, such as Django models or querysets, into native
Python data types (like dictionaries or lists) that can then be easily rendered into JSON, XML, or
other content types. Serializers also handle the reverse process, allowing you to parse incoming data
(such as JSON from an API request) and convert it back into complex types.

Key Functions of Serializers

1. Data Validation:
◦ Serializers validate incoming data against de ned elds and constraints, ensuring
that the data meets your expectations before it gets processed or saved.
2. Data Conversion:

◦ Serializers convert complex data types into a format that can be easily rendered into
a response (e.g., JSON). This is essential for creating APIs.
3. Deserialization:

◦ When receiving data from clients, serializers can parse and validate the data,
converting it into Django objects or other complex data types.
4. Handling Relationships:

◦ Serializers can handle relationships between different models (e.g., foreign keys) and
can serialize nested objects.

from django.db import models

class Car(models.Model):
make = models.CharField(max_length=100)
model = models.CharField(max_length=100)
year = models.PositiveIntegerField()
price = models.DecimalField(max_digits=10, decimal_places=2)

def __str__(self):
return f"{self.make} {self.model} ({self.year})"

from rest_framework import serializers


from .models import Car

class CarSerializer(serializers.ModelSerializer):
class Meta:
model = Car
elds = ['id', 'make', 'model', 'year', 'price'] # Specify which elds to include
fi
fi
fi
fi
APIs in Django

Using APIs in Django, especially with Django REST Framework (DRF), allows you to create
robust web services that can be consumed by various clients, such as web applications, mobile apps,
or other services. Here’s a step-by-step guide on how to set up and use APIs in Django with DRF:

You can test your API using tools like Postman, cURL, or even your web browser for GET
requests.

Example API Endpoints

• GET /api/cars/ - List all cars


• POST /api/cars/ - Create a new car
• GET /api/cars/<id>/ - Retrieve a speci c car by ID
• PUT /api/cars/<id>/ - Update a speci c car by ID
• DELETE /api/cars/<id>/ - Delete a speci c car by ID
Summary

Using Django REST Framework, you can quickly set up a RESTful API for your Django
application. The steps involve creating models, serializers, and views, and mapping them to URLs.
DRF takes care of much of the heavy lifting, including data validation, serialization, and creating a
robust API structure.

Django Shell

The Django shell is an interactive Python shell that allows you to interact with your Django
project's models and database directly. It’s an invaluable tool for testing, debugging, and performing
quick data manipulations without needing to create views or run a web server.

Common Uses of the Django Shell

1. Importing Models: You can import your models to interact with them directly. For
example, if you have a Carmodel:
python
Copy code

2.
from cars.models import Car
fi
fi
fi
3.

4. Creating and Saving Instances: You can create new instances of your models and save
them to the database:
python
Copy code

new_car = Car(make='Toyota', model='Corolla', year=2021,


price=20000.00)

5. new_car.save() # Save the car instance to the database


6.

7. Querying Data: You can perform queries to retrieve data from the database:
python
Copy code

# Retrieve all cars

8. all_cars = Car.objects.all()
9.
10. # Retrieve a car by ID
11. specific_car = Car.objects.get(id=1)
12.
13. # Filter cars by a specific attribute
14. toyota_cars = Car.objects.filter(make='Toyota')
15.

16. Updating Records: You can retrieve a record, modify it, and save the changes:
python
Copy code

car_to_update = Car.objects.get(id=1)

17. car_to_update.price = 22000.00 # Update the price


18. car_to_update.save() # Save changes to the database
19.

20. Deleting Records: To delete a record, fetch it and call the delete() method:
python
Copy code

car_to_delete = Car.objects.get(id=1)

21. car_to_delete.delete() # Delete the car instance from


the database
22.

23. Data Validation: You can perform quick data validation and checks directly in the shell:
python
Copy code

# Check if a specific car exists

24. exists = Car.objects.filter(id=1).exists()


25.

Exiting the Shell

To exit the Django shell, simply type:

python
Copy code
exit()
or press Ctrl + D.

Bene ts of Using the Django Shell

• Interactive Testing: Quickly test out snippets of code and see results immediately.
• Data Manipulation: Make direct changes to your database without needing to create a web
interface.
• Debugging: Investigate and debug issues with your models or data by directly querying and
modifying records.
fi
A.4 Theory

Django Overview:

· Django is a high-level Python web framework that encourages rapid development and clean,
pragmatic design. It follows the MVC (Model-View-Controller) architectural pattern, where:

o Model: Represents the data structure.

o View: Handles the business logic and returns the appropriate response.

o Template: De nes the presentation layer (HTML).

Django Views:

· A view function in Django is a Python function that takes a web request and returns a web
response. It can return HTML content, redirect to another URL, or return a JSON response.

Django Templates:

· Templates are HTML les that de ne how the content is presented. They allow for dynamic
content generation using Django's templating language, which includes template tags and lters.

URL Routing:

· Django uses a URL dispatcher to route incoming requests to the appropriate view based on the
requested URL pattern de ned in the urls.py le.

Django follows the MVT (Model-View-Template) architectural pattern,


which is conceptually similar to the more common Model-View-Controller
(MVC) pattern.
fi
fi
fi
fi
fi
fi
1. Model: The Model represents the data structure and the business
logic of the application. It defines the schema and the interaction
with the database. In Django, models are represented as Python
classes that define the structure of database tables.
2. Django provides an Object-Relational Mapping (ORM) system that
abstracts the database, allowing developers to work with Python
objects instead of writing raw SQL queries.
3. View: The View is responsible for handling user requests, processing
data from the Model, and rendering an appropriate response. It acts
as an intermediary between the Model and the Template. In Django,
views are Python functions or classes that take a web request and
return a web response.
4. Template: The Template is responsible for defining the structure of
the final HTML or other output that is sent to the client. Templates in
Django use a template language that allows for the inclusion of
dynamic content from the View.

CRUD Operations in Django

CRUD stands for Create, Read, Update, and Delete, which are the four basic operations used to
manage data in a database cane be handled by the function in views.py.

1. Retrieve Employees Ordered by Salary: Implement functionality to list employees ordered by


their salary.

2. Filter Employees by Salary Range: Allow users to lter employees based on a speci c salary
range.

Hints:

myproject/ # Root directory of your Django project

├── myproject/ # Django settings and con guration les

│ ├── __init__.py

│ ├── settings.py # Project settings

│ ├── urls.py # Root URL con guration

│ ├── asgi.py

│ └── wsgi.py
fi
fi
fi
fi
fi

├── myapp3/ # Application directory (the app for employee management)

│ ├── __init__.py

│ ├── admin.py

│ ├── apps.py # Application con guration

│ ├── forms.py # Django forms for Employee model

│ ├── migrations/ # Database migrations for the app

│ │ └── __init__.py

│ ├── models.py # Employee model de nition

│ ├── views.py # Application views (CRUD and employee-related operations)

│ ├── urls.py # URL routing for the app (employee CRUD operations)

│ └── templates/

│ ├── employee_form.html # Template for employee creation and update

│ ├── employee_list.html # Template to display employee list

│ └── employee_con rm_delete.html # Template for employee deletion con rmation

├── manage.py

└── db.sqlite3

A.4 Theory: CRUD Operations in Django using DRF

CRUD stands for Create, Read, Update, and Delete, which are the four basic operations used to
manage data in a database cane be handled by the function in views.py using DRF

Steps for Setting up Django REST Framework (DRF)

1. Install DRF: pip install djangorestframework

2. Con gure Django Settings:

1. Add 'rest_framework' to your INSTALLED_APPS list in settings.py:


fi
fi
fi
fi
fi
INSTALLED_APPS = [

...,

'rest_framework',

3. Create Serializer for Already created Employee Model: In myapp/serializers.py:

from rest_framework import serializers

from .models import Employee

class EmployeeSerializer(serializers.ModelSerializer):

class Meta:

model = Employee

elds = ['id', 'name', 'salary']

4. Update Views with API Endpoints: In myapp/views.py:

from rest_framework.decorators import api_view

from rest_framework.response import Response

from rest_framework import status

from .models import Employee

from .serializers import EmployeeSerializer

# List Employees or Create new Employee

@api_view(['GET', 'POST'])

def employee_list(request):

if request.method == 'GET':

employees = Employee.objects.all()

serializer = EmployeeSerializer(employees, many=True)


fi
return Response(serializer.data)…..

….

You might also like