Home > Net >  How to compare list of models with queryset in django?
How to compare list of models with queryset in django?

Time:01-26

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: <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?

CodePudding user response:

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

CodePudding user response:

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

CodePudding user response:

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)
.values('id'))
if {'id': self.context.get("request").user.id} in users_list:
    # do what you want if that's True or anything

users_list.

  • Related