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

      From Data To Decisions: UX Strategies For Real-Time Dashboards

      September 13, 2025

      Honeycomb launches AI observability suite for developers

      September 13, 2025

      Low-Code vs No-Code Platforms for Node.js: What CTOs Must Know Before Investing

      September 12, 2025

      ServiceNow unveils Zurich AI platform

      September 12, 2025

      Building personal apps with open source and AI

      September 12, 2025

      What Can We Actually Do With corner-shape?

      September 12, 2025

      Craft, Clarity, and Care: The Story and Work of Mengchu Yao

      September 12, 2025

      Distribution Release: Q4OS 6.1

      September 12, 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

      Optimizely Mission Control – Part III

      September 14, 2025
      Recent

      Optimizely Mission Control – Part III

      September 14, 2025

      Learning from PHP Log to File Example

      September 13, 2025

      Online EMI Calculator using PHP – Calculate Loan EMI, Interest, and Amortization Schedule

      September 13, 2025
    • Operating Systems
      1. Windows
      2. Linux
      3. macOS
      Featured

      sudo vs sudo-rs: What You Need to Know About the Rust Takeover of Classic Sudo Command

      September 14, 2025
      Recent

      sudo vs sudo-rs: What You Need to Know About the Rust Takeover of Classic Sudo Command

      September 14, 2025

      Dmitry — The Deep Magic

      September 13, 2025

      Right way to record and share our Terminal sessions

      September 13, 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:

    <span class="hljs-keyword">from</span> django.db <span class="hljs-keyword">import</span> models
    
    <span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">Book</span>(<span class="hljs-params">models.Model</span>):</span>
        title = models.CharField(max_length=<span class="hljs-number">100</span>)
        author = models.CharField(max_length=<span class="hljs-number">50</span>)
        published_date = models.DateField()
        price = models.DecimalField(max_digits=<span class="hljs-number">5</span>, decimal_places=<span class="hljs-number">2</span>)
    

    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
    <span class="hljs-built_in">cd</span> 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:

    <span class="hljs-keyword">from</span> django.db <span class="hljs-keyword">import</span> models
    
    <span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">Author</span>(<span class="hljs-params">models.Model</span>):</span>
        name = models.CharField(max_length=<span class="hljs-number">100</span>)
        birthdate = models.DateField()
    
        <span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">__str__</span>(<span class="hljs-params">self</span>):</span>
            <span class="hljs-keyword">return</span> self.name
    
    
    <span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">Book</span>(<span class="hljs-params">models.Model</span>):</span>
        title = models.CharField(max_length=<span class="hljs-number">200</span>)
        author = models.ForeignKey(Author, on_delete=models.CASCADE)
        summary = models.TextField()
        isbn = models.CharField(max_length=<span class="hljs-number">13</span>, unique=<span class="hljs-literal">True</span>)
        published = models.DateField()
        price = models.DecimalField(max_digits=<span class="hljs-number">6</span>, decimal_places=<span class="hljs-number">2</span>)
    
        <span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">__str__</span>(<span class="hljs-params">self</span>):</span>
            <span class="hljs-keyword">return</span> 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 = [
        <span class="hljs-comment"># other apps</span>
        <span class="hljs-string">'books'</span>,
    ]
    

    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:

    <span class="hljs-keyword">from</span> books.models <span class="hljs-keyword">import</span> Author, Book
    <span class="hljs-keyword">from</span> datetime <span class="hljs-keyword">import</span> date
    
    <span class="hljs-comment"># Create an author</span>
    jane = Author.objects.create(name=<span class="hljs-string">"Jane Austen"</span>, birthdate=date(<span class="hljs-number">1775</span>, <span class="hljs-number">12</span>, <span class="hljs-number">16</span>))
    
    <span class="hljs-comment"># Create a book</span>
    book = Book.objects.create(
        title=<span class="hljs-string">"Pride and Prejudice"</span>,
        author=jane,
        summary=<span class="hljs-string">"A novel about manners and marriage in early 19th-century England."</span>,
        isbn=<span class="hljs-string">"1234567890123"</span>,
        published=date(<span class="hljs-number">1813</span>, <span class="hljs-number">1</span>, <span class="hljs-number">28</span>),
        price=<span class="hljs-number">9.99</span>
    )
    
    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=<span class="hljs-literal">False</span>)
    

    2. Auto Timestamps

    These are super useful when tracking created or updated times:

    created_at = models.DateTimeField(auto_now_add=<span class="hljs-literal">True</span>)
    updated_at = models.DateTimeField(auto_now=<span class="hljs-literal">True</span>)
    

    3. Model Meta Options

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

    <span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">Book</span>(<span class="hljs-params">models.Model</span>):</span>
        <span class="hljs-comment"># fields...</span>
    
        <span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">Meta</span>:</span>
            ordering = [<span class="hljs-string">'published'</span>]
    

    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:

    <span class="hljs-keyword">from</span> django.contrib <span class="hljs-keyword">import</span> admin
    <span class="hljs-keyword">from</span> .models <span class="hljs-keyword">import</span> 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

    Repurposing Protein Folding Models for Generation with Latent Diffusion
    Artificial Intelligence

    Repurposing Protein Folding Models for Generation with Latent Diffusion

    September 14, 2025
    Artificial Intelligence

    Scaling Up Reinforcement Learning for Traffic Smoothing: A 100-AV Highway Deployment

    September 14, 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

    Cisco warns of max severity RCE flaws in Identity Services Engine

    Security

    Handle Fluent Values as Arrays with Laravel’s array() Method

    Development

    Qwen3 family of reasoning models now available in Amazon Bedrock Marketplace and Amazon SageMaker JumpStart

    Machine Learning

    HTML Email Accessibility Report 2025

    News & Updates

    Highlights

    Windows 11 24H2 breaks SAP GUI (SAPLogon.exe) with ntdll.dll error (0xc0000409)

    April 18, 2025

    Windows 11 24H2 KB5055523 has yet another bug that causes issues with SAP GUI. Previously,…

    Android Show: Google to Unveil OS Future Before I/O 2025

    April 29, 2025

    CVE-2025-52895 – Frappe SQL Injection Vulnerability

    June 30, 2025

    Rilasciato Firefox 140: Novità e Miglioramenti del Browser Open Source

    June 24, 2025
    © DevStackTips 2025. All rights reserved.
    • Contact
    • Privacy Policy

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