kaan_atakan
kaan_atakan

Reputation: 4047

Specifying a relation through multiple shared foreign keys

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

Upvotes: 1

Views: 26

Answers (1)

willeM_ Van Onsem
willeM_ Van Onsem

Reputation: 476729

For an Alpha model named some_alpha you can retrieve the Beta items with:

Beta.objects.filter(gamma__alpha=some_alpha, delta__alpha=some_alpha)

We thus will check that the relations that span over gamma and delta refer to the same alpha object.

Upvotes: 0

Related Questions