0

I would like to run a query in django using a list. I found a similar post on stack overflow that got me to where I am now, but I can't seem to get my code to work. I think the only difference is that I am using REST. My code below is throwing the error unsupported operand type(s) for &: 'Build' and 'Build'

What I am expecting is that the query will return all entries where the author_id matches any value in the machinesOwned list.

from .models import Build
import operator
from functools import reduce

class buildStatsAPI(generics.ListCreateAPIView):#for build stats
    permission_classes = (permissions.IsAuthenticated,)
    serializer_class = buildStatsAPI_serializer
    def get_queryset(self):
    machinesOwned = [4,5,7,9]
    query = reduce(operator.and_, (Build(author_id= item) for item in [machinesOwned]))
    return Build.objects.filter(query,deleted = 0,).values() 
2
  • What is Build here? It looks a bit strange that you query with Build(..) & Build(..) etc as a filtering object? Should these be Q objects? Commented Feb 3, 2019 at 16:55
  • Ah yes that is part of my issue I think. However I changed to query = reduce(operator.and_, (Q(author_id= item) for item in [machinesOwned])) and it returns : int() argument must be a string, a bytes-like object or a number, not 'list' Commented Feb 3, 2019 at 17:00

1 Answer 1

1

You can dynamically create a list of Q objects, but you might be able to do this a bit more efficiently another way:

Build.objects.filter(
    deleted=0,
    author_id__in=machinesOwned,
).values() 

Otherwise if you're set on your current approach:

from django.db.models import Q
query = reduce(operator.and_, (Q(author_id= item) for item in machinesOwned))
Build.objects.filter(query,deleted = 0,).values()
Sign up to request clarification or add additional context in comments.

1 Comment

I sure love this community! Thank you for the solution. Your first suggestion is much more efficient, and works as I expected

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.