1

If I had the following related models:

class User(models.Model):
    ...


class Identity(models.Model):
    user = models.ForeignKey(User, on_delete=models.PROTECT)
    category = models.CharField(max_length=8, choices=IDENTITY_CATEGORIES)
    ...

How could I query for users with multiple email identities, where multiple Identity instances exist of category "email" which point to the same User.

I've seen that Django 1.8 introduced Conditional Expressions, but I'm not sure how they would apply to this situation.

1

1 Answer 1

1

By applying django.db.models.Sum, here's one way of achieving it:

from django.db.models import Case, IntegerField, Sum, When


def users_with_multiple_email_identities():
    """
    Return a queryset of Users who have multiple email identities.
    """
    return (
        User.objects
        .annotate(
            num_email_identities=Sum(
                Case(
                    When(identity__category='email', then=1),
                    output_field=IntegerField(),
                    default=Value(0)
                )
            )
        )
        .filter(num_email_identities__gt=1)
    )

So, we use use .annotate() to create an aggregate field representing the number of email identities per user, and then apply .filter() to the results to return only users with multiple email identities.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.