djangomany-to-many

Getting list of distinct ManyToManyField objects


Given these models:

class Format(models.Model):
    name = models.CharField(unique=True)
    # More fields...

class Release(models.Model):
    formats = models.ManyToManyField(Format, blank=True)
    # More fields...

When I have a queryset of Releases (e.g. through releases = Release.objects.filter(foo='bar')), how do I get a list of the formats in that queryset, as objects and distinct?

Neither of the following achieve this:

# produces a list of dicts with IDs, not distinct e.g. [ { 'formats': 1 }, { 'formats': 2 }, { 'formats': 1 } ]:
formats = releases.values('formats')

# produces a list of IDs, not distinct, e.g. [ 1, 2, 1 ]:
formats = releases.aggregate(arr=ArrayAgg('platforms'))['arr']

The only way I can think of is manually creating a list by looping through the IDs, checking if it already exists in the list, and if not adding it with formats.append(Format.objects.get(id=the_id)), but I would really like to avoid doing that, if possible.


Solution

  • Query in reverse:

    Format.objects.filter(release__foo='bar').distinct()

    an extra advantage is that these are Format objects, so with all fields, and methods that you defined on the Format model "included".