Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 761
jul Avatar asked Dec 02 '25 09:12

jul


1 Answers

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.

like image 179
Ahsan Avatar answered Dec 04 '25 01:12

Ahsan



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!