Let's say we have 4 models, lets call them Alpha, Beta, Gamma, and Delta and the first two are something like:
class Alpha(models.Model):
gamma = models.ForeignKey(Gamma, on_delete=models.RESTRICT)
delta = models.ForeignKey(Delta, on_delete=models.RESTRICT)
text = models.CharField(max_length=1024)
class Meta:
constraints = [
models.UniqueConstraint(fields=['gamma_id', 'delta_id'])
]
class Beta(models.Model):
gamma = models.ForeignKey(Gamma, on_delete=models.RESTRICT)
delta = models.ForeignKey(Delta, on_delete=models.RESTRICT)
value = models.IntegerField()
As you can see the two foreign keys can be used to associate any number of rows from Beta with one row from Alpha. There is essentially a one to many relationship between Beta and Alpha.
For various reasons it is not feasible to replace the two foreign keys in Beta with a foreign key to Alpha.
Is there a way to define a relationship on Alpha that returns all the rows from Beta that have the same gamma_id and delta_id
For an
Alphamodel namedsome_alphayou can retrieve theBetaitems with:We thus will check that the relations that span over
gammaanddeltarefer to the samealphaobject.