Search code examples
jquerydjangomany-to-many

Django many-to-many query dict representation


I have this query

        campaign_query = Campaign.objects.filter(id__in=campaign_ids).select_related('campaign_manager__name').prefetch_related('products').values(
            'id', 'name', 'campaign_manager_id', 'campaign_manager__name', 'products'
        )

Which is supposed to return a dict representation of my Campaign obj.

The problem is that 'products' is a many to many relationship and is only returning the first product, not a list of all of them.

Return example:

 <QuerySet [{'id': 19, 'name': 'Gby id', 'campaign_manager_id': 3, 'campaign_manager__name': '', 'products': 34}]>

What I want

 <QuerySet [{'id': 19, 'name': 'Gby id', 'campaign_manager_id': 3, 'campaign_manager__name': '', 'products': [34,35,36]}]>

Solution

  • if you use Postgres for your database, theres ArrayAgg

    from django.contrib.postgres.aggregates.general import ArrayAgg
    
    campaign_query = Campaign.objects.filter(
            id__in=campaign_ids
        ).select_related(
            'campaign_manager__name'
        ).prefetch_related(
            'products'
        ).values(
            'id', 'name', 'campaign_manager_id', 'campaign_manager__name',
            products=ArrayAgg('products__id')
        )
    

    I haven't test it yet, but hope it works.