Python  

Django Web Framework Model Class with Example

Django Model attributes represent the database for each field or column, and also generate a database-access API automatically. In Python, the Django model class is a subclass of the Django DB class django. DB. Models. Model. Django web framework apps interact with the DB using Django’s ORM (Object-Relational Mapping).

With the quick example of the model class, we will see here.

Models.py

from django.db import models

class Book(models.Model):
    Book_id = models.CharField(max_length=100)
    Book_title = models.CharField(max_length=200)   
    Book_author = models.CharField(max_length=100)
    Book_published_date = models.DateField()       
    isbn = models.CharField(max_length=13, unique=True) 
    pages = models.IntegerField()             
    available = models.BooleanField(default=True)

    def __str__(self):
        return f"{self.title} by {self.author}"

Model class Components

Component Purpose
models.Model Its a Base class of Django models class which was created
Book_id ID for the primary key in the table entry
Book_title, Book_author Text fields in the model class
__str__ method Returning a readable string to print an object

View.py

from django.shortcuts import render
from .models import Book

def get_books(request):
    books = Book.objects.filter(available=True).order_by('-Book_published_date')
    return render(request, 'books.html', {'books': books})

Template page

<!DOCTYPE html>
<html>
<head>  
</head>
<body>
    <ul>
        {% for book in books %}
            <li>
                <strong>{{ book.Book_title }}</strong> by {{ book.Book_author }}<br>
                Published on: {{ book.Book_published_date }}<br>
                ISBN: {{ book.isbn }}<br>
                Pages: {{ book.pages }}
            </li>
        {% empty %}
            <li>No books available.</li>
        {% endfor %}
    </ul>
</body>
</html>

Output

Book Title Book Author Published Date ISBN Pages Available
Beginners William S. 2023-05-10 9781234567890 320 Yes
Tricks Dan Bader 2022-11-15 9789876543210 280 Yes