About Lesson
What is a Model?
A model is a Python class that defines the structure of a database table.
Defining a Model
-
- Open the
models.py
file in your app directory. - Create a model class that inherits from
models.Model
:
- Open the
from django.db import models
class Book(models.Model):
title = models.CharField(max_length=100)
author = models.CharField(max_length=50)
publication_date = models.DateField()
isbn = models.CharField(max_length=13, unique=True)
available = models.BooleanField(default=True)
Field Types
Django provides various field types for defining data:
CharField
: Stores strings of a specified maximum length.IntegerField
: Stores integers.DateField
: Stores date values.BooleanField
: StoresTrue
orFalse
.
Metadata and Methods
- Meta Class: Add metadata about your model.
- Custom Methods: Add functionality to the model.
class Meta:
ordering = ['-publication_date'] # Sort by newest first
def __str__(self):
return self.title # String representation of the object
Join the conversation