Skip to content

Instantly share code, notes, and snippets.

@EricTatua
Forked from jhgaylor/through_relationships.py
Created November 12, 2021 11:49
Show Gist options
  • Save EricTatua/8ddf68a5895504891b84b86b53a9e811 to your computer and use it in GitHub Desktop.
Save EricTatua/8ddf68a5895504891b84b86b53a9e811 to your computer and use it in GitHub Desktop.

Revisions

  1. @jhgaylor jhgaylor revised this gist Jun 27, 2013. 2 changed files with 19 additions and 15 deletions.
    15 changes: 0 additions & 15 deletions gistfile1.txt
    Original file line number Diff line number Diff line change
    @@ -1,15 +0,0 @@
    class A(models.Model):
    things = models.ManyToMany(through=Through)

    class B(models.Model):
    ...

    class Through(models.Model):
    a = models.ForeignKey(A)
    b = models.ForeignKey(B)
    extra = models.Boolean()

    #this would do it
    Through.objects.filter(b=instance_of_b, extra=True)
    #is there a way to go this way?
    A.things.filter(extra=True)
    19 changes: 19 additions & 0 deletions through_relationships.py
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,19 @@
    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)
  2. @jhgaylor jhgaylor created this gist Jun 27, 2013.
    15 changes: 15 additions & 0 deletions gistfile1.txt
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,15 @@
    class A(models.Model):
    things = models.ManyToMany(through=Through)

    class B(models.Model):
    ...

    class Through(models.Model):
    a = models.ForeignKey(A)
    b = models.ForeignKey(B)
    extra = models.Boolean()

    #this would do it
    Through.objects.filter(b=instance_of_b, extra=True)
    #is there a way to go this way?
    A.things.filter(extra=True)