jul
jul

Reputation: 37474

Adding an attribute to all my models

I would like to separate my models in different blocks in my admin's index (see this question).

In order to achieve that, I'd like to add an attribute "admin_group" to all my models. Then I'll override AdminSite.app_index and create a custom admin/app_index.html to group models by "admin_group" and show them in different blocks in my admin's index.

I can just add an attribute "admin_group" to my models, as shown below:

class model1(models.Model):
    # ...
    admin_group = "group1"

class model2(models.Model):
    # ...
    admin_group = "group1"

class model3(models.Model):
    # ...
    admin_group = "group2"

but I'm wondering whether there's a cleaner solution.

Note: I don't want to use the Meta option app_label, because it messes up the database requests.

Upvotes: 3

Views: 82

Answers (1)

Ahsan
Ahsan

Reputation: 11832

You can make a Parent class with that group field and inherit all your model classes with Parent class.

class Parent(models.Model):
    GROUP_CHOICES = [
        (u'1', u'Group1'),
        (u'2', u'Group2'),
        ...
       ]
   admin_group = models.CharField(_("Admin group"), max_length=1, choices = GROUP_CHOICES)

class model1(Parent):
    # ...


class model2(Parent):
    # ...

model1 and model2 now have admin_group field.

Upvotes: 2

Related Questions