Can I filter a django model using a python list?

Say I have a model Person object that has a Name field. And I have a list of people:

l = ['Bob','Dave','Jane']

I would like to return a list of all Person entries where the first name is not in the list of names defined in l.

What is the most pythonic way to do this?

EDIT: Having thought about this, I tried to make sure that the Person list does not contain the list l, which is not in the Person table. Is there an effective way to do this? I can think of several ways, not sure how effective.

+3
source share
2 answers

Rename lto read:

names = ['Bob','Dave','Jane']

Person.objects.[exclude][1](Name__[in][2]=names)

1: ( "EDIT" ):

present = Person.objects.values_list('Name', flat=True)
absent = set(names) - set(present)   
# or, if you prefer named functions to the set operator '-'
absent = set(names).difference(present) 

, " " ( "-" ) ( ).

+3

:

Person.objects.exclude(name__in=['Bob','Dave','Jane'])

+4

Source: https://habr.com/ru/post/1739659/


All Articles