(This seems to be a common question based on the "Questions that may already have your answer" list, but none of those has helped me.)
I have a several models with multi-table inheritance.
In admin (and later, in the front-end app), I need to have a list of all things in the base class, and also be able to identify which child (or grandchild) class they belong to.
I am trying to use Inheritance Manager for this. No luck so far.
class Entry(models.Model):
name = models.CharField(max_length=200)
description = models.TextField(max_length=500)
uuid = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False)
slug = models.SlugField(unique=True)
objects = InheritanceManager()
def get_queryset(self, request):
qs = self.model.objects.get_queryset()
ordering = self.get_ordering(request)
if ordering:
qs = qs.order_by(*ordering)
return qs
def __str__ (self):
return self.name + " entry"
class Person(Entity):
first_name = models.CharField(max_length=100)
last_name = models.CharField(max_length=100)
def __str__ (self):
return self.name + " Person"
Adding the string "person" and "Entry" is just a test.
Lists of Entities just show Entry
, even if is also(actually) a person.
I would like to be able to write into Entry.__str__
something that would show the final subclass. That way I could get a list of entries and see:
Bob (Person)
ABC Co. (Organization)
Great Expectations (Book)
I had the same issue, and found hacks to it one way or another. But it never felt clean. I ended up using django-polymorphic ...
When we store models that inherit from a Project model...
Project.objects.create(topic="Department Party") ArtProject.objects.create(topic="Painting with Tim", artist="T. Turner") ResearchProject.objects.create(topic="Swallow Aerodynamics", supervisor="Dr. Winter")
...and want to retrieve all our projects, the subclassed models are returned!
Project.objects.all() [ <Project: id 1, topic "Department Party">, <ArtProject: id 2, topic "Painting with Tim", artist "T. Turner">, <ResearchProject: id 3, topic "Swallow Aerodynamics", supervisor "Dr. Winter"> ]
Using vanilla Django, we get the base class objects, which is rarely what we wanted:
Project.objects.all() [ <Project: id 1, topic "Department Party">, <Project: id 2, topic "Painting with Tim">, <Project: id 3, topic "Swallow Aerodynamics"> ]
Hope that helps!
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.