开发者

Can I filter a django model with a python list?

开发者 https://www.devze.com 2022-12-25 18:34 出处:网络
Say I have a model object \'Person\' defined, which has a field called \'Name\'. And I have a list of people:

Say I have a model object 'Person' defined, which has a field called 'Name'. And I have a list of people:

l = ['Bob','Dave',开发者_运维问答'Jane']

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

What is the most pythonic way of doing this?

EDIT: After thinking about it, what I really was trying to do is come up with a sub list of l that wasn't present in the Person table. Is there an efficient way of doing this? I can think of a few ways, not sure how efficient though.


This should work:

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


Renaming l for readability:

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

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

UPDATE 1: Answer to the second question (in your 'EDIT' paragraph):

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) 

Yes, the "right hand side" of difference (but not '-') accepts any iterable (I had to look it up to confirm).

0

精彩评论

暂无评论...
验证码 换一张
取 消