Skip to content

Instantly share code, notes, and snippets.

@carymrobbins
Created February 13, 2014 16:35
Show Gist options
  • Save carymrobbins/8978615 to your computer and use it in GitHub Desktop.
Save carymrobbins/8978615 to your computer and use it in GitHub Desktop.
Access a Many to Many model in Django.
from django.db import models
# Given the following classes:
class Foo(models.Model):
name = models.TextField()
class Bar(models.Model):
name = models.TextField()
foos = models.ManyToManyField(Foo)
# Query the underlying many to many table directly.
def main():
foos = Foo.objects.filter(name='foo')
print(Bar.foos.through.objects.filter(foo__in=foos))
# This works as well.
print(Bar.foos.through.objects.filter(foo__name='foo'))
# Just to make things clear.
from django.db.models.base import ModelBase
assert isinstance(Bar.foos.through, ModelBase)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment