1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91
|
from django.db import models
from polymorphic.models import PolymorphicModel
from polymorphic.showfields import ShowFieldContent, ShowFieldTypeAndContent
class Project(ShowFieldContent, PolymorphicModel):
"""Polymorphic model"""
topic = models.CharField(max_length=30)
class ArtProject(Project):
artist = models.CharField(max_length=30)
class ResearchProject(Project):
supervisor = models.CharField(max_length=30)
class UUIDModelA(ShowFieldTypeAndContent, PolymorphicModel):
"""UUID as primary key example"""
uuid_primary_key = models.UUIDField(primary_key=True)
field1 = models.CharField(max_length=10)
class UUIDModelB(UUIDModelA):
field2 = models.CharField(max_length=10)
class UUIDModelC(UUIDModelB):
field3 = models.CharField(max_length=10)
class ProxyBase(PolymorphicModel):
"""Proxy model example - a single table with multiple types."""
title = models.CharField(max_length=200)
def __unicode__(self):
return f"<ProxyBase[type={self.polymorphic_ctype}]: {self.title}>"
class Meta:
ordering = ("title",)
class ProxyA(ProxyBase):
class Meta:
proxy = True
def __unicode__(self):
return f"<ProxyA: {self.title}>"
class ProxyB(ProxyBase):
class Meta:
proxy = True
def __unicode__(self):
return f"<ProxyB: {self.title}>"
# Internals for management command tests
class TestModelA(ShowFieldTypeAndContent, PolymorphicModel):
field1 = models.CharField(max_length=10)
class TestModelB(TestModelA):
field2 = models.CharField(max_length=10)
class TestModelC(TestModelB):
field3 = models.CharField(max_length=10)
field4 = models.ManyToManyField(TestModelB, related_name="related_c")
class NormalModelA(models.Model):
"""Normal Django inheritance, no polymorphic behavior"""
field1 = models.CharField(max_length=10)
class NormalModelB(NormalModelA):
field2 = models.CharField(max_length=10)
class NormalModelC(NormalModelB):
field3 = models.CharField(max_length=10)
|