Home > Mobile >  Python, django filter by kwargs or list, inclusive output
Python, django filter by kwargs or list, inclusive output

Time:09-23

I want to get get account Ids that will be associated with determined list of ids, currently I filter by one exactly id and I would like to input various Ids so I can get a Wider result.

My code:

from typing import List
from project import models

def get_followers_ids(system_id) -> List[int]:
    return list(models.Mapper.objects.filter(system_id__id=system_id
    ).values_list('account__id', flat=True))

If I run the code, I get the Ids associated with the main ID, the output will be a list of ids related to the main one (let's say, "with connection to"):

Example use:

system_id = 12350
utility_ids = get_followers_ids(system_id)
print(utility_ids)

output:

 >>> [14338, 14339, 14341, 14343, 14344, 14346, 14347, 14348, 14349, 14350, 14351]

But I would like to input more variables avoiding to fell in a for loop, which will be slow because it will do many requests to the server.

The input I would like to use is a list or similar, it should be able to input various arguments at a time.

And the output should be a list of relations (doing the least number of requests to DB), example

if id=1 is related to [3,4,5,6]

and if id=2 is related to [5,6,7,8]

The output should be [3,4,5,6,7,8]

CodePudding user response:

you can use the Field lookups, in your case use "In" lookup

so:

# system_ids is now a list
def get_followers_ids(system_ids) -> List[int]:
    # here add in the end in filter field the "__in"
    return list(models.Mapper.objects.filter(system_id__id__in=system_ids
    ).values_list('account__id', flat=True))

system_ids = [12350, 666]
utility_ids = get_followers_ids(system_ids)
print(utility_ids)
  • Related