I have two models that inherit from a base model:
serial = models.CharField("serial number", max_length=9, primary_key=True)
abstract = True
dpi = models.CharField("print resolution", max_length=24)
ip_address = models.GenericIPAddressField(null=True, blank=True)
So I want to have cleaner python code, obviously my
BaseDevice class has many more data that is used in all it’s children.
I want to make an admin view, that works for all
Devices - so all classes that inherit
BaseDevice´ (which is abstract=True
). I have already sometimes combined querysets using itertools chain()` method, so I tried that but failed:
def get_queryset(self, request):
return chain(PrintDevice.objects.all(), NetworkDevice.all())
Something’s wrong with your database installation. Make sure the appropriate database tables have been created, and make sure the database is readable by the appropriate user.
How can I extend the queryset of my admin to display all the possible devices? Is it unwise to use abstract classes when displaying parts of them in the admin?
Short answer: You don’t.
Longer answer: Django doesn’t “know” or “understand” what the relationships are between two classes that may both inherit from one (or more) common parent classes.
If this is a true requirement, then don’t use the admin here. Create your own view for this.
Going back to the official Django admin docs:
If you need to provide a more process-centric interface that abstracts away the implementation details of database tables and fields, then it’s probably time to write your own views.
Defining a model as “abstract=True” may reduce the number of definitions needed by the child classes, but does not otherwise establish any type of relationship.
As far as the database itself is concerned,
BaseDevice doesn’t even exist.
Trying to chain two different querysets is not going to give you the expected results under any reasonable circumstances. You might be able to create a union between the two, assuming you do the work to ensure that both querysets return the same number of columns and that you have a way to identify the base type, but making that work well in the admin is going to be a whole different story.
Thanks for that valuable insight and thank you again for the long answer. I was afraid it might be like this and I managed to create the
union with manually populated querysets. But ultimatively you are right - I just saved some models.py lines and did not win a reduced complexity with my approach, so I let it go …