What is models.py? It’s Working and Architecture
models.py is a Python module in a Django app that defines the structure of your database tables through classes. Each class represents a table, and each attribute within the class represents a field in that table. Django uses this file to create the database schema and handle database queries. Explore What is models.py? It’s Working and Architecture. Learn how it handles data modeling and streamlines database interactions effectively. Enroll Today.
Key Components of models.py
- Model Class: Each class in models.py extends django.db.models.Model, which tells Django to treat it as a model that should map to a database table.
- Fields: Attributes of the model, such as CharField, IntegerField, DateTimeField, etc., represent columns in the table.
- Methods: Define custom methods to add functionality, such as __str__ for better representation in the admin panel.
Step-by-step Example: models.py File
Let’s create an example models.py file for a simple blog application.
- Basic models.py Creation Create a new Django app (e.g., blog):
python manage.py startapp blog
- Define models.py Open blog/models.py and create a model for blog posts:
from django.db import models
from django.utils import timezone
from django.contrib.auth.models import User
class Post(models.Model):
title = models.CharField(max_length=200)
content = models.TextField()
author = models.ForeignKey(User, on_delete=models.CASCADE)
created_at = models.DateTimeField(default=timezone.now)
updated_at = models.DateTimeField(auto_now=True)
def __str__(self):
return self.title
- Explanation:
- CharField: A field for small-to-medium-sized strings, like the title of the blog post.
- TextField: Used for longer text, such as the body content of the post.
- ForeignKey: Creates a many-to-one relationship (e.g., each post is associated with one user, but a user can have many posts).
- DateTimeField: Stores date and time. The default argument can set the field to the current date and time.
- __str__: Returns the string representation of the object, helpful in Django’s admin panel.
- Database Migration After defining the model, run the following commands to create and apply the migration:
python manage.py makemigrations
python manage.py migrate
- makemigrations: Generates the migration file based on the changes in models.py.
- migrate: Applies the generated migration to the database, creating or updating the table.
- Register the Model in admin.py To make the model accessible through the Django admin interface:
from django.contrib import admin
from .models import Post
admin.site.register(Post)
- Using the Model in Views Now that the Post model is defined and registered, you can use it in views to create, read, update, and delete data.
from django.shortcuts import render
from .models import Post
def post_list(request):
posts = Post.objects.all()
return render(request, ‘blog/post_list.html’, {‘posts’: posts})
- Basic Template to Display Posts Create a post_list.html template in the blog/templates/blog directory to render the list of posts:
<h1>Blog Posts</h1>
{% for post in posts %}
<h2>{{ post.title }}</h2>
<p>{{ post.content }}</p>
<small>By {{ post.author }} on {{ post.created_at }}</small>
{% endfor %}
For Free, Demo classes Call: 020-71177359
Registration Link: Click Here!
Practical Details
- Field Options: Django fields like CharField, IntegerField, BooleanField, etc., come with various parameters such as max_length, null, blank, default, etc., to customize how data is stored.
- Relationships: Use ForeignKey, OneToOneField, and ManyToManyField to define relationships between models.
- Custom Methods: Adding methods such as get_absolute_url() can help in generating URLs for model instances.
Common Commands for Database Interaction
Create an object:
post = Post.objects.create(title=‘My First Post’, content=‘This is the content’, author=request.user)
Query objects:
posts = Post.objects.filter(author__username=‘john’)
Update an object:
post.title = ‘Updated Title’
post.save()
Delete an object:
post.delete()
This practical guide gives you the building blocks to create models in Django, migrate them, and use them in views and templates. Feel free to expand your models with additional fields and methods as needed!
Do visit our channel to learn More: Click Here
Author:-
Sagar Gade
Call the Trainer and Book your free demo Class for Django Call now!!!
| SevenMentor Pvt Ltd.
© Copyright 2021 | SevenMentor Pvt Ltd