E
E
Empty User2020-07-03 20:26:31
Django
Empty User, 2020-07-03 20:26:31

How to get records where IDs are inside an array?

Good day! There are two match objects, team

class Match(models.Model):
      .....

class Team(models.Model):
      match = models.ForeignKey(Match, related_name="command", on_delete=models.CASCADE)
      .....


There is an array of team IDs, arr = [2, 6]

The task is to get all matches in which only teams from the arr array participate.
Match.objects.filter(command__in=arr).distinct() displays all matches where at least one element matches. How to write a query to display only those matches in which there are only these teams?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
D
Dmitry, 2020-07-04
@dimash07

from django.models.db import Q
ids = [2, 6]
q = Q()
for id in ids:
    q &= Q(command__id=id)
qs = Match.objects.filter(q).distinct()

Although this code is designed for the fact that you can have ids of any size. In your case, it's easier to do this:
from django.models.db import Q
Match.objects.filter(Q(command__id=arr[0]) & Q(command__id=arr[1])).distinct()

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question