Creating models
This episode covers :-
1) How to create and use models.
2) How to make database queries.
- Setup :-
Terminal
cp -fr 13-Static-Files-CSS 14-Models
cd 14-Models
source ../venv/bin/activate
- Creating the Flower model :-
Edit myapp models.py file:
myapp/models.py
├── 14-Models
│ ├── myapp
│ │ ├── models.py # < here
Add a Flower class and a title attribute:
myapp/models.py
from django.db import models
class Flower(models.Model):
title = models.CharField(max_length=255, default='')
Edit myapp admin.py file and register the Flower class:
myapp/admin.py
from django.contrib import admin
from myapp.models import Flower
admin.site.register(Flower)
Apply changes to the database and create a superuser:
Terminal
python manage.py makemigrations
python manage.py migrate
python manage.py runserver
python manage.py createsuperuser
You can use admin as the username and password. Just bypass the validation:
Terminal
Bypass password validation and create user anyway? [y/N]: y
Superuser created successfully.
Visit http://127.0.0.1:8000admin and add a few flowers. Here are some examples from Wikipedia:
- https://samuli.to/Amelanchier-alnifolia
- https://samuli.to/Amelanchier-asiatica
- https://samuli.to/Agapanthus
“Flower object (n)” is not very descriptive representation for a Flower object. Let’s show the title instead.
Edit models.py file and add a __str__ method:
myapp/models.py
from django.db import models
class Flower(models.Model):
title = models.CharField(max_length=255, default='')
def __str__(self):
return self.title
Now we can see the actual titles:
Listing Flower
Let’s list the flowers on the frontpage. Edit myapp index.html template and replace the contents with these lines:
myapp/templates/myapp/index.html
{% extends 'base/base.html' %}
{% block content %}
{% for flower in flowers %}
<div class="card">
<div class="card-body">
<h5 class="card-title">{{ flower.title }}</h5>
<p class="card-text">Lorem ipsum, dolor sit amet cons\
ectetur adipisicing elit.</p>
<a href="adminmyapp/flower/{{ flower.id }}/change/"\
class="card-link">Edit</a>
<a href="adminmyapp/flower/{{ flower.id }}/delete/"\
class="card-link">Delete</a>
</div>
</div>
{% endfor %}
{% endblock %}
Edit the myapp views.py file and replace the contents with these lines:
myapp/views.py
from django.shortcuts import render
from myapp.models import Flower
def index(request):
flowers = Flower.objects.all()
return render(request, 'myapp/index.html', {'flowers': \
flowers })
Now the frontpage looks something like this:
For now the edit and delete functionality is provided through the admin user interface.
- In Details :-
Explaining models :-
Models offer an abstracted way to interact with data. With Django’s database-access API you can use Flower.objects.all() to get all Flowers rather than doing queries like "SELECT * FROM Flowers".
To create models we subclass django.db.models.Model:
myapp/models.py
from django.db import models
class Flower(models.Model):
title = models.CharField(max_length=255, default='')
We import other modules to get access to the code they contain.
- Flower class represents a database table.
- title attribute represents a database field.
CharField is used for smaller size strings. Use TextField for larger texts.
To make a model editable in the admin interface, you have to register it as we did in the myapp admin.py file:
myapp/admin.py
admin.site.register(Flower)
Makemigrations command creates the migration files. These files are usually moved with rest of the code and applied in other environments:
Terminal
python manage.py makemigrations
Migrate command updates the database schema. This will create the Flower table and title field:
Terminal
python manage.py migrate
Createsuperuser command creates the main administration account. This user has all permissions by default. Make sure to use a decent password and unique username in the production server:
Terminal
python manage.py createsuperuser
- Returning a string representation :-
__str__ method returns a human-readable representation of an object. In this case we use the title attribute to create it:
myapp/models.py
def __str__(self):
return self.title
You could also format the return string using multiple fields like this:
Formatting the representation
def __str__(self):
return f"Title: {self.title}, Date: {self.date}"
- Making database queries :-
Now that we have models, we can interact with the database using an API. Flower.objects.all() returns a QuerySet that contains all Flower objects in the database:
Fetch objects from a database
flowers = Flower.objects.all()
In the myapp views.py file we pass the flowers QuerySet to the template using {'flowers': flowers }:
myapp/views.py
def index(request):
flowers = Flower.objects.all()
return render(request, 'myapp/index.html', {'flowers': \
flowers })
In the template we use a for loop to go through all the objects:
myapp/templates/myapp/index.py
{% for flower in flowers %}
{{ flower.title }}
{% endfor %}
Summary
- Django’s database-access API makes it easy to interact with persistent data.
- You have to register a model with admin.site.register() to make it available in the admin interface.
- __str__ is used to compute a human-readable representation of an object.
- You can see it in use in the admin interface.
- You can use a for loop to iterate through a QuerySet in templates.
PRINT THIS POST




No comments:
Post a Comment
If you have any doubts. Please let me know.