1 year ago

#383360

test-img

andrepz

Generic ManyToMany for multiple inherited models

First of all, the following code is not an example of best practices in DB modelling and I know it, unfortunately, this is already made and it's what it is. Remodelling everything is just not an option.

I have the following models:

models.py

class OtherModel(models.Model):
    ...


class AbstractSite(models.Model):
    class Meta:
        abstract = True


class Site(AbstractSite):
    ...

class Banner(Site):
    data = models.ManyToManyField(OtherModel, blank=True)

The issue is, this many-to-many is supposed to be present both in the Site and the Banner models.

I've tried to specify it in the Abstract Model, and it created a site_data table, but data saved in the Banner model was also populating this table, instead of populating a banner_data as I was expecting.

The easiest way is to create a new field in the Site model, named differently from the data field in the Banner model, but this doesn't seem to be correct, since any new child model would need a new table being declared. I was expecting to find a way to dynamically allocate this in the DB.

Is there a way to create a dynamic through parameter that follows the class child class name?

python

django

postgresql

django-models

many-to-many

0 Answers

Your Answer

Accepted video resources