Question

Let's say I have a base class with, for example:

class Base(models.Model):
    name = models.CharField(max_length=50, blank=False, null=False)
    value1 = models.CharField(max_length=50)
    value2 = models.CharField(max_length=50)

Now, I'm inputting several types of objects into the table, some of which use parts of the data, some of which use other parts, all of them using some common part (name in this example).

I want a complete listing, but I want to have different views when I click into an object, depending on it's type. Changes in the modelAdmin include: one of the classes uses inlines, others don't, list_display varies, one has extra CSS, etc, etc. Basically we're talking about different modelAdmins.

Alternatives I'm thinking: one is that each of those types subclasses Base, i.e.:

class Type1(Base):
    pass

class Type2(Base):
    pass

and then I define a modelAdmin for each of them, and one for the Base class just to get the table listing everything. In this one I would override the links so they don't go to /app/base/id, but instead to /app/type1/id, /app/type2/id, etc depending on the type. For each of these, I modify the modelAdmins so after saving they go back to /app/type

A different alternative would be having a single model and a single modelAdmin, and overriding every single method I'm using for change_view to consider what type of object it's rendering, i.e., get_inline_instances, get_formsets, whatever I need to modify list_display, list_display_links, list_filter, etc.

The first alternative looks way cleaner to me, although I'm not sure how to modify the link other than defining a method in the modelAdmin with the correct call to reverse and adding that method as a column in list_display.

Is there an easier way I'm missing?. How would you do it?.

Oh, and it HAS to use the admin. I'd rather do this using views, or separate models, but sadly this is the way it has to be. The High Command wants everything in one single table.

Thanks!.

Edit: also, I just found this and it looks good:

http://django-polymorphic.readthedocs.org/en/latest/admin.html

Était-ce utile?

La solution

Django-Polymorphic definitely seems the way to go. It's easy to use and automatically gives me the correct modelAdmin when I click through a base object, something I couldn't replicate with Proxies.

Only problem is a table is created for each child class, even if the child class doesn't have any additional fields, and an extra query is performed per child class even though nothing is recovered from it (only column in the table is a foreign key to the base object).

But it works. I can live with that.

Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top