Home > Software engineering >  make query for filtering where object is in queryset
make query for filtering where object is in queryset

Time:12-31

ive got three models

-Company

-Queue

-User

Company and Queue have a one to one relationship

User and Queue have a many to many relationship. Users can be in many queues, and more importantly, a queue can contain many users

How do I write a query that filters for companies whose queue contains a specified user? joined_companies should contain companies whose queues contain user

(companies.queue.users is a queryset of Users)

    def get(self, request, **kwargs):
        user = request.user
        
        companies = Company.objects.all()
        
        joined_companies = companies.filter(queue__users__contains=user)

CodePudding user response:

Just remove contains, you also do not need the first query, the scope of filter is all objects:

    user = request.user
    companies = models.Company.objects.filter(queue__users=user)

contains lookup does not work, because you are looking for an User object instance instead of an value:

username = request.user.username
companies = models.Company.objects.filter(queue__users__username__contains=username)
  • Related