Querying through four models in Django

I have a data model similar to this (simplified):

class Mobility(models.Model):
    pass

class Transfer(models.Model):
    mobility = models.ForeignKey(Mobility)

class Organism(models.Model):
    pass

class TransferLine(models.Model):
    transfer = models.ForeignKey(Transfer)
    organism = models.ForeignKey(Organism)

I have an instance of Mobility and an instance of Organism, and I'd like to get all the TransferLine instances that are related to both (to the Organism directly, and to the Mobility through the Transfer).

This question differs from this other question in that in my case, I need to go through two relations and there's also a compound condition.

Upvotes: 1

Views: 45

Answers (2)

Todor
Todor

Reputation: 16010

Another approach would be to use the ForeignKey reverse relation:

tlines = my_organisam.transferline_set.filter(transfer__mobility=my_mobility)

Upvotes: 1

Just use the double-underscore notation to make lookups that span relationships. In this case, it could be done like this:

transfer_lines = TransferLine.objects.filter(transfer__mobility=mobility, 
                                             organism=organism)

Upvotes: 1

Related Questions