0
0
Djangoframework~5 mins

Defining models with fields in Django

Choose your learning style9 modes available
Introduction

Models let you organize and save data in your app. Fields define what kind of data each part holds.

You want to store user information like names and emails.
You need to keep track of products with prices and descriptions.
You want to save blog posts with titles and content.
You need to record dates and times for events.
You want to link related data, like authors to books.
Syntax
Django
from django.db import models

class ModelName(models.Model):
    field_name = models.FieldType(options)

Each field represents a column in the database.

FieldType can be CharField, IntegerField, DateTimeField, etc.

Examples
This model stores a person's name and age.
Django
class Person(models.Model):
    name = models.CharField(max_length=100)
    age = models.IntegerField()
This model stores blog posts with title, content, and publish date.
Django
class BlogPost(models.Model):
    title = models.CharField(max_length=200)
    content = models.TextField()
    published = models.DateTimeField()
This model stores products with a name and price with two decimals.
Django
class Product(models.Model):
    name = models.CharField(max_length=100)
    price = models.DecimalField(max_digits=6, decimal_places=2)
Sample Program

This model defines a Book with title, author, and year. The __str__ method shows a friendly name.

Django
from django.db import models

class Book(models.Model):
    title = models.CharField(max_length=150)
    author = models.CharField(max_length=100)
    published_year = models.IntegerField()

    def __str__(self):
        return f"{self.title} by {self.author} ({self.published_year})"
OutputSuccess
Important Notes

Always set max_length for CharField to limit text size.

Use appropriate field types to match the data you want to store.

After defining models, run migrations to create database tables.

Summary

Models organize data with fields as columns.

Each field type controls what data is saved.

Define models before saving or querying data.