FIlter instances that has the same field as instance id of which I provide in one query?

Viewed 16

I have simple model:

class User(models.Model):
    group_uuid = models.UUIDField(default=uuid.uuid4)

Let say i have only available user_id, and I need to retrieve all the users that has the same group_uuid as user id of which I have in user_id variable.

Not sure if we can utilize F or Subquery object in some ways.

So we want to achieve this in one query:

user = User.objects.get(id=user_id)
User.objects.filter(group_uuid=Subquery(user))

This obviously is NOT making one query, but it should be possible to make it in one right?

1 Answers

You can simply work with the .group_id of the user:

user = User.objects.get(id=user_id)
User.objects.filter(group_uuid=user.group_uuid)

Or if you need one query, you can work with .filter(…) instead of .get(…) for the user:

user_uuids = User.objects.filter(id=user_id).values('group_uuid')
User.objects.filter(group_uuid__in=user_uuids)

Since QuerySets are lazy, it will not perform the user_uuids query, but simply encode this as a subquery.

That being said, using subqueries are not always more efficient. Especially MySQL is known to recalculate the subquery per element, even if the subquery is "constant" with respect to that item.

Related