Skip to content

Instantly share code, notes, and snippets.

@jerinisready
Forked from jhgaylor/through_relationships.py
Created November 14, 2018 04:44
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jerinisready/fdbf741533959da2edf1a91d9253935c to your computer and use it in GitHub Desktop.
Save jerinisready/fdbf741533959da2edf1a91d9253935c to your computer and use it in GitHub Desktop.
Example of using a through model in Django and filtering by a value on the custom through model.
class A(models.Model):
things = models.ManyToManyField("B", through=ThroughModel)
class B(models.Model):
text = models.TextField()
class ThroughModel(models.Model):
a = models.ForeignKey(A)
b = models.ForeignKey(B)
extra = models.BooleanField()
#this will return a list of ThroughModel objects
ThroughModel.objects.filter(b=instance_of_b, extra=True)
#this will return a list of A objects based on an extra field on the through table
A.objects.filter(things__ThroughModel__extra=True)
#keep in mind that limiting by one of the foreign keys on the through model is easier
A.objects.filter(things=instance_of_b)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment