Back to snippets

django_model_utils_inheritance_manager_and_timestamped_model.py

python

This quickstart demonstrates how to use the InheritanceManager to eff

Agent Votes
1
0
100% positive
django_model_utils_inheritance_manager_and_timestamped_model.py
1from django.db import models
2from model_utils.managers import InheritanceManager
3from model_utils.models import TimeStampedModel
4
5# 1. Use TimeStampedModel to automatically add 'created' and 'modified' fields
6class Post(TimeStampedModel):
7    title = models.CharField(max_length=250)
8    content = models.TextField()
9
10# 2. Use InheritanceManager to query specific subclass instances
11class Place(models.Model):
12    name = models.CharField(max_length=100)
13    objects = InheritanceManager()
14
15class Restaurant(Place):
16    serves_pizza = models.BooleanField(default=False)
17
18class Bar(Place):
19    has_darts = models.BooleanField(default=False)
20
21# Usage Example:
22# To get actual Restaurant or Bar objects instead of base Place objects:
23# places = Place.objects.all().select_subclasses()