Welcome back! In the last lesson, we discussed the process of setting up and connecting to an SQLite3 database within your Django project. Now, it's time to elevate our skills by defining and exporting Django models. Models are a crucial part of the data layer in Django applications, acting as the blueprint for database tables. Understanding how to work with models will enable you to manage complex data structures efficiently.
In this lesson, we'll focus on defining Django models to represent and interact with data in a structured format. Specifically, you'll learn how to:
- Create Django Models: Define models in your
models.py
file to represent database tables. - Save and Retrieve Data: Use Django models to interact with the database, performing operations like saving and querying records.
Let's look at an example:
In project/myapp/models.py
, we'll define a simple model for an Item
with a name field:
Python1from django.db import models 2 3class Item(models.Model): 4 name = models.CharField(max_length=200) 5 6 def __str__(self): 7 return self.name
This model defines a table with one column, name
, and specifies that entries in this column should be no longer than 200 characters.
Then, in project/myapp/views.py
, we can include this model in our views to save and retrieve data:
Python1from django.http import HttpResponse 2from .models import Item 3 4def add_and_get_items(request): 5 item = Item(name='Item 1') 6 item.save() 7 8 items = Item.objects.all() 9 return HttpResponse(items)
This short snippet demonstrates how to create a new Item
, save it to the database, and retrieve all items using Django's ORM. Let's break down these steps in more detail:
- We use the defined
Item
model to create a new item with the name 'Item 1'. - We save the new item to the database using the
save()
method. This operation will automatically create a table namedmyapp_item
in the database if it doesn't already exist. Notice that the name of the table is derived from the app name (myapp
) and the model name (Item
) in lowercase. - After saving the item, we retrieve all items from the database using the
objects.all()
method. This method returns a queryset containing all items in theItem
table (equivalent toSELECT * FROM myapp_item
in SQL).
Defining and working with Django models is fundamental for any Django developer. Models are the link between the database and your application's logic, ensuring that complex data can be managed efficiently and consistently. By mastering this skill, you'll be able to develop robust, scalable applications that handle data effortlessly.
Excited to jump in? Let's move on to the practice section, where you'll get hands-on experience defining and using Django models. Happy coding!