Creating Models in Django


Django models are the backbone of any Django application. They provide the foundation for the ORM (Object-Relational Mapping) by defining the structure of your database tables.

This article demonstrates how to create models in Django with examples.

Step 1: Define a Model

A model is a Python class that subclasses django.db.models.Model. Here's an example:

            
    from django.db import models

    class Author(models.Model):
        first_name = models.CharField(max_length=50)
        last_name = models.CharField(max_length=50)
        email = models.EmailField()
        birth_date = models.DateField(null=True, blank=True)

        def __str__(self):
            return f"{self.first_name} {self.last_name}"
            
        

In this example, the Author model has four fields: first_name, last_name, email, and birth_date.

Step 2: Make Migrations

After defining your model, Django needs to create the corresponding database table. Run the following commands:

            
    python manage.py makemigrations
    python manage.py migrate
            
        

Step 3: Using the Model

Now that the model is defined and migrated, you can use it to interact with the database:

            
    from myapp.models import Author

    # Create a new author
    new_author = Author(first_name="Jane", last_name="Doe", email="jane.doe@example.com")
    new_author.save()

    # Query authors
    all_authors = Author.objects.all()

    # Filter authors
    filtered_authors = Author.objects.filter(last_name="Doe")

    # Update an author
    author = Author.objects.get(id=1)
    author.first_name = "John"
    author.save()

    # Delete an author
    author.delete()
            
        

Step 4: Add More Fields

You can add more fields to your model as needed. For example:

            
    class Book(models.Model):
        title = models.CharField(max_length=100)
        publication_date = models.DateField()
        author = models.ForeignKey(Author, on_delete=models.CASCADE)

        def __str__(self):
            return self.title
            
        

The Book model includes a ForeignKey to the Author model, establishing a one-to-many relationship.

Step 5: Admin Integration

To manage your models in Django's admin interface, register them in the admin.py file:

            
    from django.contrib import admin
    from .models import Author, Book

    admin.site.register(Author)
    admin.site.register(Book)
            
        

After registering your models, you can interact with them through the Django admin interface.

Conclusion

In this guide, we covered how to create, migrate, and use models in Django. Models are a fundamental part of building robust Django applications.





Advertisement