Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Django 1.11 - Query to exclude based on other table

Problem

I'm trying to build a system to invite people to teams so I have Team and Invitation models. I'm trying to query users that don't have a team and that aren't in the Invitations table with that team. So far I can filter the users that don't have a team but I can't figure out how to exclude users that already have an invite from that team.

What I have so far

from django.contrib.postgres.search import SearchVector

sv = SearchVector('first_name', 'last_name', 'email')
team = parsed_body['team_id']
query = parsed_body['query']
users = User.objects.annotate(search=sv).filter(search=query, profile__team=None)

Team Model

from django.db import models

class Team(models.Model):
    name = models.CharField(max_length=32, blank=False, default=None)
    description = models.TextField(max_length=512, blank=False, default=None)
    created_by = models.ForeignKey(User, on_delete=models.SET_NULL, null=True)

Invitation Model

from django.db import models

class Invitation(models.Model):
    team = models.ForeignKey(Team, on_delete=models.CASCADE)
    shifter = models.ForeignKey(User, on_delete=models.CASCADE)
like image 819
Tiago Martins Avatar asked Dec 20 '25 21:12

Tiago Martins


2 Answers

Try this,

User.objects.exclude(invitation__team=1)

Where 1 is the PK/ID of the Team instance you want to specify

like image 104
JPG Avatar answered Dec 23 '25 11:12

JPG


User.objects.filter(profile__team=None).exclude(invitation_set__team=your_team_to_exclude)
like image 37
phoibos Avatar answered Dec 23 '25 11:12

phoibos



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!