If A is a foreign key to B and C, and B and C have a M2M relationship, do you need to specify the foreign key in the models of B and C.

Hello I have been deliberating over this for ages and would like someone’s opinion.
I have the following three models:

class Commodity(models.Model): 
    commodity = models.CharField(max_length=50, primary_key=True, unique=True)
class Variety(models.Model):
    commodity = models.ForeignKey(Commodity, on_delete=models.PROTECT, related_name='Variety')
    variety_name = models.CharField(max_length=50, unique=True)
class Weighbridge(models.Model):
    tn = models.AutoField(primary_key=True) 
    variety_chosen = models.ManyToManyField(to=Variety, related_name='weighbridge') 

The relationship I am trying to capture is this:

My question is - is it correct to explicitly write commodity as a foreign key to both weighbridge and variety or is it ok to leave it the way I have done in the code - where the relationship between weighbridge and variety is the only one explicitly defined?
Weighbridges should have a ForeignKey relationship to Commodity but is the implicit relationship through variety enough?

Any opinions would be greatly appreciated.

Thanks in advance,

That is going to depend upon what the actual relationships are among these entities in the real world that you are trying to model.

We would need to understand what these models are supposed to represent and what the interactions and relationships are among them to be able to advise you regarding the models that need to be created.

Thanks Ken,

Well every weighbridge ticket has a commodity (only one commodity per ticket). The same commodity can appear on several different weighbridge tickets hence the foreign key relationship.

Each commodity has several different types of varieties hence the foreign key relationship

Each weighbridge ticket can have several varieties but those varieties all have to belong to the same commodity.

Does this make sense?

Good, clear enough.

Good, clear enough.


So based upon the information provided here, I would leave your models exactly as they are defined. I don’t see anything to be gained by addition additional ForeignKey fields in these models.

1 Like