Created
February 13, 2014 16:35
-
-
Save carymrobbins/8978615 to your computer and use it in GitHub Desktop.
Access a Many to Many model in Django.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 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