The Admin & the ORM
Manage your data with Django’s free admin panel, and query it with the ORM.
What you will learn
- Use the built-in admin
- Query data with the ORM
- Create and read records
The free admin panel
Django gives you a full admin site for free — a ready-made web dashboard for adding, editing and deleting your data. Getting it working takes just two steps: create an admin user to log in with, then register the model you want to manage.
First, create a superuser. This command asks you for a username, email and password in the terminal:
python manage.py createsuperuser # make an admin loginA superuser is an admin account that can log into /admin and do anything. Next, tell the admin which model to show by registering it:
# blog/admin.py
from django.contrib import admin
from .models import Post
admin.site.register(Post)We import the Post model and call admin.site.register(Post). That single line tells the admin to build add/edit/delete screens for posts automatically.
Getting the admin working, step by step:
- Run
python manage.py createsuperuserand answer the prompts to make an admin account (username, email, password). - In
blog/admin.py,importyour model and calladmin.site.register(Post)so the admin knows about it. - Start the server with
python manage.py runserverand openhttp://127.0.0.1:8000/adminin your browser. - Log in with the superuser you just created.
- Click Posts to add, edit and delete records through the ready-made screens — no extra code needed.
Note: Visit /admin and log in — you can now add, edit and delete posts with no extra code.
Query with the ORM
The ORM (Object-Relational Mapper) lets you read and write the database using plain Python instead of SQL. Every model gets an objects manager with handy methods:
Post.objects.all() # all posts
Post.objects.get(id=1) # one post
Post.objects.filter(title="Hi") # matching posts
Post.objects.create(title="New", body="...") # createWhat each line does: all() fetches every post. get(id=1) fetches the one post with that id (and errors if there is not exactly one). filter(title="Hi") fetches all posts whose title is "Hi" (could be zero, one, or many). create(...) makes a brand-new post and saves it to the database in one step.
Note: Output (running Post.objects.all() in the shell):
<QuerySet [<Post: My first post>, <Post: Hello Django>]>
Django turned your Python call into a SQL SELECT and returned the matching rows as a list-like QuerySet.
Q. How do you get all records of a Post model?
✍️ Practice
- Create a superuser and register your model in the admin.
- Add a few records via the admin, then fetch them with
objects.all().
🏠 Homework
- Use the ORM to create, read and filter records in the Django shell (python manage.py shell).