Custom QuerySet for a Django admin action

# Customers model

Customers(models.Model):
    name = models.CharField(max_length=255)
    emails = ArrayField(models.EmailField(), default=list, blank=True)
    ...
    ...
    ...

I have a QuerySet which has all the information according to the model of all the selected customers.

# Django admin action

    def get_email_ids(self, request, queryset):
        """
        QuerySet here is all the information according to the model of all the selected customers.
        """
        # new_queryset = ?
        return generate_csv(
            request,
            queryset,
            filename="email-ids.csv",
        )

I want a new custom QuerySet that only has the customer name and email id's. But it should be in the following way. If a customer has 10 email id's then there should be 10 rows for that customer in the QuerySet.

e.g.

customer1 email1@email.com
customer1 email2@email.com
customer1 email3@email.com
customer1 email4@email.com
customer2 emailother@email.com

How to achieve this for new_queryset?

I used the following way to get the desired data.

Customers.objects.filter(is_active=True)
        .annotate(
            emails =Func(F("emails"), function="unnest")
        )
        .values(
            "name",
            "emails",
        )
        .distinct()
Back to Top