ManyToManyField lookup which Django seems doesn't support yet
I want to do something which it seems Django doesn't officially supports it yet.
Here goes the models.py
class Report(models.Model):
# using default `AutoField`, `id` / `pk`
pass
class BulkOfReports(models.Model):
id = models.UUIDField(
primary_key=True,
default=uuid.uuid7,
editable=False,
verbose_name="ID",
)
reports = models.ManyToManyField(
Report,
verbose_name=_("laporan-laporan"),
related_name="bulk_of_reports",
)
And for example if those BulkOfReports
can be represented like this:
BulkOfReports = [Reports_ids]
Then with data like this:
A = [1, 2, 3]
B = [1, 2]
C = [1]
D = [2]
E = [3]
How could I get the A option only with Django's QuerySet
API?
I have tried this:
self.reports.filter(id__in=[1, 2, 3])
But what I have is all of those QuerySet
mentioned above:
A, B, C, D, E
You can filter with:
from django.db.models import Count, Q
BulkOfReports.objects.alias(
nrep=Count('reports'),
nfilter=Count('reports', filter=Q(reports__id__in=my_report_ids)),
).filter(nrep=len(my_report_ids), nfilter=len(my_report_ids))
hope I understand your question correctly...
try this:
bulk_reports_ids = BulkOfReports.objects.filter(
reports__id__in=[1, 2, 3]
).values_list('id', flat=True)
.values_list()
method refrenced in django documantation