What are Database Models & Admin Panel in Django?
In this article series on Django, we will learn what Database Models & Admin Panels are in Django.
In Django, a database model is a class that represents a table in a database. It defines the fields of the table and the data types of those fields. Django uses these models to interact with the database and perform CRUD (create, read, update, delete) operations on the data.
Here’s an example of a simple database model in Django:
from django.db import models
class Blog(models.Model):
title = models.CharField(max_length=200)
body = models.TextField()
created_at = models.DateTimeField(auto_now_add=True)
updated_at = models.DateTimeField(auto_now=True)
def __str__(self):
return self.title
In this example, the Blog
model has four fields: title
, body
, created_at
, and updated_at
. The CharField
and TextField
fields are used to store character and text data, respectively. The DateTimeField
fields are used to store date and time data and have the auto_now_add
and auto_now
arguments set, which will automatically set the field to the current date and time when the model is created or updated.
Once you have defined your models, you can use Django’s ORM (Object-Relational Mapper) to create, read, update, and delete data in the database. For example, you can create a new blog post like this:
blog_post = Blog(title='My Blog Post', body='This is the body of my blog post.')
blog_post.save()
The Django admin panel is a built-in tool that allows you to manage your database models and the data stored in them. It provides an interface for creating, editing, and deleting records in the database and can be easily customized to suit your needs.
To use the Django admin panel, you will need to register your models with the admin site. Here’s an example of how you might do this:
from django.contrib import admin
from .models import Blog
admin.site.register(Blog)
This will allow you to manage your Blog
models in the Django admin panel. You can then access the admin panel by visiting the /admin/
URL on your site.
Using database models and the Django admin panel, you can easily manage and interact with your data in Django. Whether you’re building a simple blog or a complex web application, these tools make it easy to work with your data and keep it organized.
To conclude, database models and the Django admin panel are important tools in Django for managing and interacting with data. Database models allow you to define the fields and data types of a database table and perform CRUD operations on the data. The Django admin panel is a built-in tool that provides an interface for managing your database models and the data stored in them. By using database models and the Django admin panel, you can easily manage and organize your data in Django, making it a powerful and flexible choice for web development.
Hope you get some insights into Django from this article. See you again in another blog.