Django Models Deeper: Mastering Advanced Features and Practical Uses

Django Models 심화 기능 참고 이미지1

Hello, everyone! Fundamentals of Django Modelsand go deeper with us. If you've used Django, you know how powerful Models can be, but today we're going to go beyond the basics, Django We're going to explore the Models deep features.

Leverage custom managers, abstract models, and multiple databases and other real-world techniques will be explained in a simple way with code examples. By the end of this post, you'll be able to master Django Models!

Django Models 심화 기능 참고 이미지1

1. Django Models in depth: Custom Manager

Beyond the managers Django provides out of the box, custom managers give you more flexibility to retrieve data. For example, let's create a manager that only retrieves data that meets certain conditions.

커스텀 매니저(Custom Manager) 이미지
from django.db import models

class PublishedManager(models.Manager):
    def get_queryset(self):
        return super().get_queryset().filter(status='published')

class Post(models.Model):
    title = models.CharField(max_length=200)
    content = models.TextField()
    status = models.CharField(max_length=10, choices=[('draft', 'Draft'), ('published', 'Published')])

    objects = models.Manager() # default manager
    published = PublishedManager() # custom manager

    def __str__(self):
        return self.title

Code commentary

  • class PublishedManager(models.Manager):
    • Django's Managerto define a custom manager class.
    • This class is designed to allow you to apply specific conditions to a database lookup and return a custom queryset.
  • def get_queryset(self):
    • get_queryset method is responsible for returning the query set.
    • return super().get_queryset().filter(status='published')
      • The default query set (super().get_queryset()) to add a filter to the status If the field value is 'published'Set to lookup only data that is
      • This method allows you to use the published You can selectively manage only the data in a state.
  • objects = models.Manager()
    • Define the default manager for the model.
    • objectsprovides a default queryset that includes all data.
    • It can be used with custom managers to provide additional ways to view data in your model.
  • published = PublishedManager()
    • Connect a custom manager to your model to create a status='published' Define a manager that returns a query set with conditions applied.
    • With this manager, you can use the Post.published.all()to easily look up data that meets specific conditions.
  • class Post(models.Model):
    • A model class that manages blog posts.
    • The main fields are
      • title: The title of the post (CharField), with a maximum length of 200 characters.
      • content: The field that stores the body content of the post (TextField).
      • status: Post status (draft or published) to store the data. choices option to limit the possible values.
  • def __str__(self):
    • When representing an object as a string, you can use a post's title (title) to be returned.
    • For example, from the Django admin page or shell, you can use the Post When you output an object, it displays a title.

2. Django Models Deeper: Abstract Model

Abstract models are useful for defining fields that are used in common across multiple models. Models that inherit from an abstract model will automatically include the fields from the abstract model.

추상 모델(Abstract Model) 이미지
class TimeStampedModel(models.Model):
    created_at = models.DateTimeField(auto_now_add=True)
    updated_at = models.DateTimeField(auto_now=True)

    class Meta:
        abstract = True

class Post(TimeStampedModel):
    title = models.CharField(max_length=200)
    content = models.TextField()

    def __str__(self):
        return self.title

Code commentary

  • class TimeStampedModel(models.Model): Defines an abstract model class.
  • created_at = models.DateTimeField(auto_now_add=True): Automatically save the time the model was created.
  • updated_at = models.DateTimeField(auto_now=True): Automatically save the time the model was updated.
  • class Meta: abstract = True: Declares that this model is an abstract model.
  • class Post(TimeStampedModel): TimeStampedModelwhich inherits from Post Define a model.

3. Deepening Django Models: Utilizing Multiple Databases

Django can use multiple databases at the same time. For example, you can have a read-only database and a write-only database.

class User(models.Model):
    name = models.CharField(max_length=100)
    email = models.EmailField()

    class Meta:
        db_table = 'user'
        using = 'default' use # default database

class Log(models.Model):
    action = models.CharField(max_length=100)
    timestamp = models.DateTimeField(auto_now_add=True)

    class Meta:
        db_table = 'log'
        using = 'logs_db' # using a separate database

Code commentary

  1. class User(models.Model):
    • Manage user dataA Django model class for creating and manipulating Django models.
    • It primarily stores username and email information.
    • The main fields are
      • name: A character field that can store up to 100 characters (CharField).
      • email: The field that stores the email address (EmailField), validation is automatically applied.
    Meta Classes:
    • db_table = 'user':
      • Set the name of the table to use in the database to 'user'to the default.
      • The default rule for automatically generating table names (appname_modelname) instead of the specified name.
    • using = 'default':
      • This model is based on the Django project's default database (default) in the following example.

  1. class Log(models.Model):
    • Manage log dataA Django model class for creating and manipulating Django models.
    • The main fields are
      • action: A character field that can store up to 100 characters (CharField), which stores a description of a specific action (e.g. "login", "logout").
      • timestamp: A date-time field that stores when the action occurred (DateTimeField).
        • auto_now_add=True: Automatically save the current time when the object is first created.
    Meta Classes:
    • db_table = 'log':
      • Set the name of the table to use in the database to 'log'to the default.
    • using = 'logs_db':
      • This model is based on the 'logs_db'called Separate databasesto use the
      • The project's configuration file (settings.py) in the 'logs_db'must be defined.

Finalize

Now that you know the deeper features of Django Models, you should be able to use them more effectively. If you have any further questions, please leave them in the comments. Let's learn together! 😊

# Glossary

  1. Custom ManagerA customized manager that allows you to retrieve only data that meets certain conditions.
  2. Abstract ModelA model that defines fields that are used in common across multiple models.
  3. Multiple DatabasesA technique for using multiple databases simultaneously in one application.

Similar Posts