How to compare list of models with queryset in django?


I have a serializer:

class MySerializer(serializers.ModelSerializer):
    class Meta:
        model = models.MyClass
        fields = "__all__"

    def validate(self, data):
        user = self.context.get("request").user
        users = data.get("users")
        users_list = User.objects.filter(organization=user.organization)
        return data

users will print a list of models like this:
[<User: User 1>, <User: User 2>]

users_list will display a queryset:
<QuerySet [<User: User 1>, <User: User 2>, <User: User 3>]>

I want to write a query which checks if list of models e.g.users are present inside a queryset users_list. How to do that?

Asked By: Waleed Farrukh



As I can see you need to compare every User organization with request.user organization. If you have list of objects, You can do it without QuerySet:

user = self.context.get("request").user
users = data.get("users")
for u in users:
    if u.organization == user.organization:
        # do what you want if that's True or anything
return data
Answered By: NixonSparrow

You can use sets as Models are hashable if the model has a primary key:

>>> users
[<User: user1>, <User: user2>]

>>> users_list
<QuerySet [<User: user1>]>

>>> set(users).intersection(users_list)
{<User: user1>}

>>> set(users).difference(users_list)
{<User: user2>}

# and so on
Answered By: Corralien

You can get the ids of all the users and convert queryset into the list and then validate the data

users_list = list(User.objects.filter(organization=user.organization)
if {'id': self.context.get("request")} in users_list:
    # do what you want if that's True or anything


Answered By: Vikrantkumar