Re-use of M2M related through model

Hi, everyone.
This topic, probably, might not be related to Django ORM directly but to common models relations design.

I’m working with Django for a while but just recently one question has come into my mind which I never thought about.
Let’s assume we have some simple dummy models:

class ComponentSetup(models.Model):
    component = ForeignKey(Component)
    config  = ForeignKey(Config)
    qty = PositiveIntegerField(default=1)

class Component(models.Model):
    title = CharField()

class Config(models.Model):
    sku = CharField()
    components = ManyToManyFIeld(Component, through=ComponentSetup)
     

Sometimes while creating new Config we want to add some common Component instance where qty would be similar with existed ComponentSetup through model. Do we re-use through model instance in this case or creating new through instance anyway?

Example:

common_component = Component.objects.get(title="component_a")
config_A = Config.objects.create(sku="000A")
config_A.components_set.add(common_component , through_defaults={"qty": 3})

We have created new Config instance and assigned Component instance to it.
However, now I would like to create another Config instance which suppose to use the same Component instance where qty has to be 3 as well.

Do I have to repeat the step above or do something like this:

component = Component.objects.filter(title=title="component_a", componentsetup_set__qty=3).first()

or even :

component = ComponentSetup.objects.filter(component__title="component_a", qty=3).first().component
config_B = Config.objects.create(sku="000B")
config_B.components_set.add(component)

So Django creates the new ComponentSetup instance every time we need the same setup but qty is different?
Probably a common use case but I can’t get the whole picture how Django manages default intermediate M2M table under the hood.

Each of these three models, Component, Config, and ComponentSetup are representations of tables in the database.

If you are creating a new instance of Config, and want to add a relationship to an instance of Component, that relationship requires that a new instance of ComponentSetup be created, because an instance of ComponentSetup creates an association between one instance of Config with one instance of Component. Every combination of the relationship (Component, Config) are defined by a unique row in ComponentSetup

1 Like

Hello, @KenWhitesell .
Thanks a lot for clarifying as always. Just found some overengineered code in production and got frustrated if I missed something out utilizing M2M field.