Multiple models to have same M2M relation with quantity counter

Hi everyone.
Trying to figure out the right logic to assign consumables ManyToMany relations with quantity counter for multiple models.
I have a legacy code which not so easy to scale for now.
Just simplified code for understanding:

class ComponentA(models.Model):
    name = CharField()

class Config(models.Model)
    component_a = ForeignKey(ComponentA)
    component_b = ForeignKey(ComponentB)
    component_n ....

class Entity(models.Model):
    config = ForeignKey(Config)

Now I have a task to assign some accessories (1 or more) for each Component model. The Component models themselves different by mean, have some unique fields which can’t be shared between other ComponentB model etc, so can’t be merged in single model.

I’m trying to find out a clean way to implement such a functionality. My toughts:

  1. Create some AccessorySet abstract model with Many2Many field and make other components to inherit from it but in this case I have to define for each component model individual through model what doesn’t look clean and scalable at all;
  2. Create AccessorySet as normal model with a single M2M and create some OneToOne relation with every Component..N model. Then AccessorySet Many2Many field would has just single through.

Probably, it woulf be great all Component..N model to inherit from some base class using multi-table iheritance from very beginning but it feels hard to refactor it in that way with thousands of records exist in DB.
Would appreciate any help on this topic.

I would go with a more Generic Relations Approach. Something like that:

from django.contrib.contenttypes.fields import GenericForeignKey
from django.contrib.contenttypes.models import ContentType

class Accessory(models.Model):
    name = models.CharField(max_length=100)
    # other accessory fields

class ComponentAccessory(models.Model):
    accessory = models.ForeignKey(Accessory, on_delete=models.CASCADE)
    content_type = models.ForeignKey(ContentType, on_delete=models.CASCADE)
    object_id = models.PositiveIntegerField()
    component = GenericForeignKey('content_type', 'object_id')
    quantity = models.PositiveIntegerField(default=1)

    class Meta:
        unique_together = ['accessory', 'content_type', 'object_id']

class ComponentBase(models.Model):
    accessories = GenericRelation(ComponentAccessory)

    class Meta:
        abstract = True

class ComponentA(ComponentBase):
    name = models.CharField(max_length=100)
    # specific fields for ComponentA

class ComponentB(ComponentBase):
    # specific fields for ComponentB
    pass