Django
Django
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.
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.
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})"
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.
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.
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
7. Querying Data: You can perform queries to retrieve data from the database:
python
Copy code
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)
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)
23. Data Validation: You can perform quick data validation and checks directly in the shell:
python
Copy code
python
Copy code
exit()
or press Ctrl + D.
• 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 View: Handles the business logic and returns the appropriate response.
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.
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.
2. Filter Employees by Salary Range: Allow users to lter employees based on a speci c salary
range.
Hints:
│ ├── __init__.py
│ ├── asgi.py
│ └── wsgi.py
fi
fi
fi
fi
fi
│
│ ├── __init__.py
│ ├── admin.py
│ │ └── __init__.py
│ ├── urls.py # URL routing for the app (employee CRUD operations)
│ └── templates/
├── manage.py
└── db.sqlite3
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
...,
'rest_framework',
class EmployeeSerializer(serializers.ModelSerializer):
class Meta:
model = Employee
@api_view(['GET', 'POST'])
def employee_list(request):
if request.method == 'GET':
employees = Employee.objects.all()
….