[英]Django - Override Default Manager in Admin - InheritanceManager
(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. 添加字符串“ person”和“ Entry”只是一个测试。
Lists of Entities just show Entry
, even if is also(actually) a person. 实体列表仅显示
Entry
,即使实际上也是一个人。
I would like to be able to write into Entry.__str__
something that would show the final subclass. 我希望能够向
Entry.__str__
写一些可以显示最终子类的东西。 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 ...
我最终使用django-polymorphic ...
When we store models that inherit from a Project model...
当我们存储从Project模型继承的模型时...
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:
使用香草Django,我们获得了基类对象,而这正是我们想要的:
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! 希望有帮助!
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.