Steerpike
Steerpike

Reputation: 17544

Many to many lookups in Django

This is probably insultingly simple and worthy of a Nelson Muntz laugh, but I'm having a real braindead moment tryng to make many to many connections across various model relationships.

I have the following models (simplified for your enjoyment!):

class Document(models.Model):
    title = models.CharField(max_length=200)
    author = models.ForeignKey(User, blank=True)
    content = models.TextField(blank=True)
    private = models.BooleanField(default=False)

class UserProfile(models.Model):
    user = models.ForeignKey(User, unique=True)
    friends = models.ManyToManyField(User, symmetrical=False, 
                                     related_name='user_friends')
    ignored = models.ManyToManyField(User, symmetrical=False, 
                                     related_name='user_ignored')

Imaginging the following Users:

Users searching for documents should produce the following:

Basically, I'm having a mental struggle figuring out the filters to returning the querysets I described above. Anyone got any ideas?

EDIT

Thanks to Ferdinands answer below I was able to nut through to what I wanted with the start that he gave me. First off, we want to get a list of people who have friended me which is a reverse lookup through the Many to Many relationship:

friendly_authors = self.user.user_friends.all()

Get all the people I've ignored:

my_ignored = UserProfile.objects.get(user=self.user).ignored.all()

Get a list of docs I can view - docs which are viewable, mine, or written by people who have friended me but whom I haven't ignored:

docs = Document.objects.filter(
    (Q(viewable=True) | Q(author=self.user) | Q(author__in=friendly_authors))
     & ~Q(author__in=my_ignored)
)

Upvotes: 13

Views: 8480

Answers (1)

Ferdinand Beyer
Ferdinand Beyer

Reputation: 67147

It is a bit tricky, maybe you are looking for something like that:

>>> from django.db.models import Q
>>> me = User.objects.get(pk=1)
>>> my_friends = UserProfile.objects.get(user=me).friends.all()
>>> docs = Document.objects.filter(
...     Q(author=me) | (
...         Q(author__in=my_friends)
...         & ~Q(author__userprofile__ignored=me)
...     )
... )

This generates the following SQL (I did some formatting on the original output):

SELECT "myapp_document".*
FROM "myapp_document" WHERE (
    "myapp_document"."author_id" = %s
    OR (
        "myapp_document"."author_id" IN (
            SELECT U0."id" FROM "myapp_user" U0
            INNER JOIN "myapp_userprofile_friends" U1
                ON (U0."id" = U1."user_id")
            WHERE U1."userprofile_id" = %s
        )
        AND NOT (
            "myapp_document"."author_id" IN (
                SELECT U2."user_id" FROM "myapp_userprofile" U2
                INNER JOIN "myapp_userprofile_ignored" U3
                    ON (U2."id" = U3."userprofile_id")
                WHERE U3."user_id" = %s
            )
            AND "myapp_document"."author_id" IS NOT NULL
        )
    )
)

Upvotes: 9

Related Questions