Django Models Fields list, Types, Options, Relationships

Posted: October 04, 2024 | Updated: October 06, 2024

Django models play an important role in Django app development. If you want to create database tables and store information first you need to make a Django model. 

Example Model
Here's an example of a Django model using various field types:

from django.db import models

class Product(models.Model):
    name = models.CharField(max_length=100)
    description = models.TextField()
    price = models.DecimalField(max_digits=10, decimal_places=2)
    available = models.BooleanField(default=True)
    created_at = models.DateTimeField(auto_now_add=True)
    tags = models.ManyToManyField('Tag')

class Tag(models.Model):
    name = models.CharField(max_length=50)

How to create a Django Modela and migrate it into database

Open the models.py file in your Django app. first import models from django.db and create a class.

from django.db import models

class Product(models.Model):
    

Then start adding the fields you need.

from django.db import models

class Product(models.Model):
    name = models.CharField(max_length=100)

Then run the following commands to create a database table for your fields.

python manage.py makemigrations
python manage.py migrate

If you want to see and add the information to the database, log into your Django app admin account. 

You can see their no-option display about your Product class.You have to register your model in the admin.py file to see the models and add data in admin.

Open the admin.py file. Import the model and register it.

from django.contrib import admin
from .models import Product

# Register your models here.

admin.site.register(Product)

Now you can see your model in the Django admin panel.

Custom Field Options

Most fields support various options such as:

  • blank: If the field is allowed to be empty.
  • null: If the field can be set to NULL in the database.
  • default: A default value for the field.
  • choices: A set of predefined choices.

Here’s a list of commonly used field types along with a brief description of each:

Basic Field Types

CharField: A string field, for small to medium-sized text (e.g., a name).

name = models.CharField(max_length=100)

TextField: A large text field for long strings (e.g., descriptions).

description = models.TextField()

IntegerField: An integer field.

age = models.IntegerField()

© 2024 Webapptiv. All rights reserved.