Note that there are some explanatory texts on larger screens.

plurals
  1. POUsing django exclude filter problem with empty m2m field
    primarykey
    data
    text
    <p>The queryset I've constructed is incorrectly leaving out some items. I have three models in Django:</p> <pre><code>class Case(models.Model): agents = models.ManyToManyField('UserProfile', related_name='agent_of', blank=True, null=True) organization = models.ForeignKey(Organization, related_name='case_org') class UserProfile(models.Model): name = models.CharField(max_length=40) user = models.ForeignKey(User, unique=True, related_name='user_profile') organization = models.ForeignKey(Organization, related_name='org_members', blank=True, null=True) class Organization(models.Model): name = models.CharField(max_length=75) </code></pre> <p>I'm trying to build a list of unassigned cases. That is, cases that the current user is not an agent on, including cases that have no agents at all assigned to them. Here's my query:</p> <pre><code>Case.objects.filter( organization=request.user.user_profile.get().organization.id).exclude (Q(agents__user=request.user)) </code></pre> <p>This works fine for cases with other agents (UserProfile model) assigned to them. But it does not return cases with NO agent assigned to them. I'm pretty sure this has to do with the fact that cases with no agent assigned to them have no row in the intermediate table connecting UserProfiles and Cases.</p> <p>So in other words if I have these cases:</p> <p>Case/Agents</p> <p>Case1: Tom, Steve</p> <p>Case2: Steve</p> <p>Case3: Jane</p> <p>Case4: Nobody</p> <p>My query will return Case2 and Case3, but not Case4. Trying to get that Case4 included.</p> <p>Sorry if this is not very clear, any help is appreciated.</p>
    singulars
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload