Django: Retrieving IDs of manyToMany fields quickly

database, django, m2m, postgresql, python

Solution

According you have Three instances. You can use the `values_list` method to retrieve just the results and from this result get just the ID's of their `related` instances. I use the `pk` field to be my filter because i don't know your scheme, but you can use anything, just must be a `QuerySet`.

>>> result = A.objects.filter(pk=1)
>>> result.values('related__id')
[{'id': 2}, {'id': 3}]
>>> result.values_list('related__id')
[(2,), (3,)]
>>> result.values_list('related__id', flat=True)
[2, 3]

Problem

I have the following model schema in Django (with Postgres). ``` class A(Models.model): related = models.ManyToManyField("self", null=True) ``` Given a QuerySet of A, I would like to return a dictionary mapping each instance of `A` in the QuerySet to a list of `id`s of its `related` instances as quickly as possible. I can surely iterate through each A and query the related field, but is there a more optimal way?

Original source