Close Menu
    DevStackTipsDevStackTips
    • Home
    • News & Updates
      1. Tech & Work
      2. View All

      The Ultimate Guide to Node.js Development Pricing for Enterprises

      July 29, 2025

      Stack Overflow: Developers’ trust in AI outputs is worsening year over year

      July 29, 2025

      Web Components: Working With Shadow DOM

      July 28, 2025

      Google’s new Opal tool allows users to create mini AI apps with no coding required

      July 28, 2025

      I replaced my Samsung OLED TV with this Sony Mini LED model for a week – and didn’t regret it

      July 29, 2025

      I tested the most popular robot mower on the market – and it was a $5,000 crash out

      July 29, 2025

      5 gadgets and accessories that leveled up my gaming setup (including a surprise console)

      July 29, 2025

      Why I’m patiently waiting for the Samsung Z Fold 8 next year (even though the foldable is already great)

      July 29, 2025
    • Development
      1. Algorithms & Data Structures
      2. Artificial Intelligence
      3. Back-End Development
      4. Databases
      5. Front-End Development
      6. Libraries & Frameworks
      7. Machine Learning
      8. Security
      9. Software Engineering
      10. Tools & IDEs
      11. Web Design
      12. Web Development
      13. Web Security
      14. Programming Languages
        • PHP
        • JavaScript
      Featured

      Performance Analysis with Laravel’s Measurement Tools

      July 29, 2025
      Recent

      Performance Analysis with Laravel’s Measurement Tools

      July 29, 2025

      Memoization and Function Caching with this PHP Package

      July 29, 2025

      Laracon US 2025 Livestream

      July 29, 2025
    • Operating Systems
      1. Windows
      2. Linux
      3. macOS
      Featured

      Microsoft mysteriously offered a Windows 11 upgrade to this unsupported Windows 10 PC — despite it failing to meet the “non-negotiable” TPM 2.0 requirement

      July 29, 2025
      Recent

      Microsoft mysteriously offered a Windows 11 upgrade to this unsupported Windows 10 PC — despite it failing to meet the “non-negotiable” TPM 2.0 requirement

      July 29, 2025

      With Windows 10’s fast-approaching demise, this Linux migration tool could let you ditch Microsoft’s ecosystem with your data and apps intact — but it’s limited to one distro

      July 29, 2025

      Windows 10 is 10 years old today — let’s look back at 10 controversial and defining moments in its history

      July 29, 2025
    • Learning Resources
      • Books
      • Cheatsheets
      • Tutorials & Guides
    Home»Development»How to Create Models in Your Django Project

    How to Create Models in Your Django Project

    April 25, 2025

    If you’re building something with Django, there’s one thing you can’t skip: creating models. Models are the heart of any Django app. They define how your data is structured, how it’s stored in the database, and how Django can interact with it.

    Now, if you’re new to Django or still wrapping your head around the basics, don’t worry. I’ve been there too. Models might sound a bit intimidating at first, but they’re pretty straightforward once you see how they work.

    I’ll walk you through it all – step by step – so by the end of this post, you’ll not only know how to create models, but also how to use them in real projects.

    Let’s get into it.

    Here’s what we’ll cover:

    1. What is a Model in Django?

    2. How to Create Models in Django

      • Step 1: Start a Django Project (if you haven’t already)

      • Step 2: Define Your Model

      • Step 3: Register the App and Create the Database

      • Step 4: Create and Use Objects

    3. Extra Model Features That You’ll Use

      • 1. Default Values

      • 2. Auto Timestamps

      • 3. Model Meta Options

    4. Using Models in Django Admin

    5. FAQs

    6. Final Thoughts

    What is a Model in Django?

    A model in Django is just a Python class that tells Django how you want your data to look. Django takes care of the hard part (talking to the database), so you can focus on describing your data in simple Python code.

    Here’s a quick example of a basic model:

    from django.db import models
    
    class Book(models.Model):
        title = models.CharField(max_length=100)
        author = models.CharField(max_length=50)
        published_date = models.DateField()
        price = models.DecimalField(max_digits=5, decimal_places=2)
    

    Let me break it down:

    • title and author are just short pieces of text, so I’m using CharField.

    • published_date is a date – easy enough, that’s what DateField is for.

    • price is a number with decimals, so DecimalField does the job.

    Each line describes one piece of data I want to store for every book. Simple, right?

    How to Create Models in Django

    Step 1: Start a Django Project (if you haven’t already)

    If you’re brand new, first you need a Django project:

    django-admin startproject mysite
    cd mysite
    python manage.py startapp books
    

    Now you’ve got a Django app called books where you can put your models.

    Step 2: Define Your Model

    Inside your app folder (books), open models.py. That’s where you’ll define your model.

    Here’s a slightly more real-world example:

    from django.db import models
    
    class Author(models.Model):
        name = models.CharField(max_length=100)
        birthdate = models.DateField()
    
        def __str__(self):
            return self.name
    
    
    class Book(models.Model):
        title = models.CharField(max_length=200)
        author = models.ForeignKey(Author, on_delete=models.CASCADE)
        summary = models.TextField()
        isbn = models.CharField(max_length=13, unique=True)
        published = models.DateField()
        price = models.DecimalField(max_digits=6, decimal_places=2)
    
        def __str__(self):
            return self.title
    

    What’s happening here:

    • I’ve created two models: Author and Book.

    • Book has a relationship with Author using ForeignKey. That means one author can have many books.

    • I’m using __str__() to return a nice name when I look at objects in the Django admin.

    Step 3: Register the App and Create the Database

    Before Django can use your models, make sure your app is added to the project settings.

    Open mysite/settings.py and find the INSTALLED_APPS list. Add 'books', to it:

    INSTALLED_APPS = [
        # other apps
        'books',
    ]
    

    Now, run migrations to create the database tables for your models:

    python manage.py makemigrations
    python manage.py migrate
    

    This is how Django turns your Python code into actual database tables. The first command makes a migration file (basically, instructions for the database), and the second applies it.

    Step 4: Create and Use Objects

    Now you can use these models in your code. Open the Django shell:

    python manage.py shell
    

    Then try this out:

    from books.models import Author, Book
    from datetime import date
    
    # Create an author
    jane = Author.objects.create(name="Jane Austen", birthdate=date(1775, 12, 16))
    
    # Create a book
    book = Book.objects.create(
        title="Pride and Prejudice",
        author=jane,
        summary="A novel about manners and marriage in early 19th-century England.",
        isbn="1234567890123",
        published=date(1813, 1, 28),
        price=9.99
    )
    
    print(book)
    

    Django will save these to your database automatically.

    Extra Model Features That You’ll Use

    1. Default Values

    You can give a field a default value:

    is_published = models.BooleanField(default=False)
    

    2. Auto Timestamps

    These are super useful when tracking created or updated times:

    created_at = models.DateTimeField(auto_now_add=True)
    updated_at = models.DateTimeField(auto_now=True)
    

    3. Model Meta Options

    You can add class Meta to customize things like the default ordering:

    class Book(models.Model):
        # fields...
    
        class Meta:
            ordering = ['published']
    

    Using Models in Django Admin

    Django’s built-in admin panel is one of the best parts of the framework. But your models won’t show up there unless you register them.

    In books/admin.py, add:

    from django.contrib import admin
    from .models import Author, Book
    
    admin.site.register(Author)
    admin.site.register(Book)
    

    Now run:

    python manage.py createsuperuser
    

    Then go to http://127.0.0.1:8000/admin, log in, and boom – your models are there, with a full interface.

    FAQs

    Can I change a model after I’ve made it?

    Yes, but you’ll need to make a new migration:

    python manage.py makemigrations
    python manage.py migrate
    

    What databases work with Django?

    Django works with PostgreSQL, MySQL, SQLite (default), and more. Most people start with SQLite when learning because it’s easy and works out of the box.

    What’s the difference between CharField and TextField?

    Use CharField for short text with a max length (like a name or title). Use TextField for longer text (like a blog post or summary).

    Final Thoughts

    Once you understand models, the rest of Django starts to click into place. Everything – forms, views, templates – eventually connects back to the model. It’s how your app stores and works with real data.

    The best way to learn is by building something. Start small, maybe a book catalog, a task manager, or a personal blog. Add models one at a time and play with them in the admin.

    Further Resources

    • Official Django Docs – Models

    • Django Model Field Reference

    • Simple Django Tutorial – Mozilla Developer Network

    Source: freeCodeCamp Programming Tutorials: Python, JavaScript, Git & More 

    Facebook Twitter Reddit Email Copy Link
    Previous ArticleAI-generated images are a legal mess – and still a very human process
    Next Article How to Harden Your Node.js APIs – Security Best Practices

    Related Posts

    Development

    Performance Analysis with Laravel’s Measurement Tools

    July 29, 2025
    Development

    Memoization and Function Caching with this PHP Package

    July 29, 2025
    Leave A Reply Cancel Reply

    For security, use of Google's reCAPTCHA service is required which is subject to the Google Privacy Policy and Terms of Use.

    Continue Reading

    Microsoft’s Xbox PC store aggregation is rolling out for some Insiders — with Battle.net, Steam, and more in tow

    News & Updates

    Multiple SonicWall SMA 100 Vulnerabilities Let Attackers Compromise Systems

    Security

    CVE-2025-22477 – Dell Storage Center Dell Storage Manager Authentication Bypass

    Common Vulnerabilities and Exposures (CVEs)

    CVE-2025-4324 – MRCMS Cross Site Scripting Vulnerability

    Common Vulnerabilities and Exposures (CVEs)

    Highlights

    CVE-2025-47779 – Asterisk SIP Message Authentication Spoofing Vulnerability

    May 22, 2025

    CVE ID : CVE-2025-47779

    Published : May 22, 2025, 5:15 p.m. | 1 hour, 36 minutes ago

    Description : Asterisk is an open-source private branch exchange (PBX). Prior to versions 18.26.2, 20.14.1, 21.9.1, and 22.4.1 of Asterisk and versions 18.9-cert14 and 20.7-cert5 of certified-asterisk, SIP requests of the type MESSAGE (RFC 3428) authentication do not get proper alignment. An authenticated attacker can spoof any user identity to send spam messages to the user with their authorization token. Abuse of this security issue allows authenticated attackers to send fake chat messages can be spoofed to appear to come from trusted entities. Even administrators who follow Security best practices and Security Considerations can be impacted. Therefore, abuse can lead to spam and enable social engineering, phishing and similar attacks. Versions 18.26.2, 20.14.1, 21.9.1, and 22.4.1 of Asterisk and versions 18.9-cert14 and 20.7-cert5 of certified-asterisk fix the issue.

    Severity: 7.7 | HIGH

    Visit the link for more details, such as CVSS details, affected products, timeline, and more…

    Crafting SEO Content That Readers Love

    July 18, 2025

    Crestic is a configurable restic wrapper

    April 12, 2025

    8 most exciting AI features and tools revealed at Google I/O 2025

    May 20, 2025
    © DevStackTips 2025. All rights reserved.
    • Contact
    • Privacy Policy

    Type above and press Enter to search. Press Esc to cancel.