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.