Django Query where one field is duplicate and another is different

jalanga :

I want to know if I can create a query where one field is duplicate and another one is different.

Basically I want to get all UsersNames where First Name is the same and user_id is different. I did this

UserNames.objects.values("first_name", "user_id").annotate(ct=Count("first_name")).filter(ct__gt=0)

This will retrieve a list whit all Users

After tis, I make some post processing and create another query where I filter just the users with first_name__in=['aaa'] & user_id__in=[1, 2] to get the users with the same first_name but different user_id

Can I do this just in one query? or in a better way?

Willem Van Onsem :

You can work with a subquery here, but it will not matter much in terms of performance I think:

from django.db.models import Exists, OuterRef, Q

UserNames.objects.filter(
    Exists(UserNames.objects.filter(
        ~Q(user_id=OuterRef('user_id')),
        first_name=OuterRef('first_name')
    ))
)

or prior to :

from django.db.models import Exists, OuterRef, Q

UserNames.objects.annotate(
    has_other=Exists(UserNames.objects.filter(
        ~Q(user_id=OuterRef('user_id')),
        first_name=OuterRef('first_name')
    ))
).filter(has_other=True)

We thus retain UserNames objects for which there exists a UserNames object with the same first_name, and with a different user_id.

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=5595&siteId=1