Q:

Annotating User objects with filtered Groups

I am trying to serialize user data in Django Rest Framework and I wish to only return selected groups that a user is a member of. Based off if the group name ends with _certified.
I've looked at F expressions, and even Q objects but I can't seem to find an easy way to do this or if it's even possible.
NB. I'm using the built-in User and Group models.
My expected result is
{
    "User": {
        ...
        "Groups": ['role1_certified', 'role2_certified' ...] 
    }
}

Groups should only contain groups that end in _certified

A:

Based on Yahor's comment the solution I have come to is as follows.
from django.contrib.postgres.aggregates import ArrayAgg
from django.db.models import Q

user = User.objects.annotate(certified_groups=ArrayAgg(
    'groups__name', filter=Q(groups__name__endswith='_certified')))

