如何检查值是否在Django的模型列表的字段中出现?

时间:2018-08-02 22:58:56

标签: python django python-3.x django-models

我有一个Django模型列表,我想检查字符串值是否出现在列表中ANY模型的特定字段中。请参见下面的示例:

class something:
    animals = [] #type: list[Animals]

   def does_atleast_one_animal_make_that_sound(animal_sound):
       if animal_sound in ...# for each animal in animals, turn animal.sound into a list
            print('One of the animals in the list makes this sound')
       else:
            print('No animal makes this sound')

我如何正确地用“ ...”编写函数的一部分?

1 个答案:

答案 0 :(得分:0)

如果数据库中存在模型实例,则可以使用任何列出的方法(第一种和第二种基于this answer中的思想):

1)Queryset的values_list

class something:
    animals = [] #type: list[Animals]
    animals = [animal.id for animal in animals]

    def does_atleast_one_animal_make_that_sound(animal_sound):
       if animal_sound in Animal.objects.filter(id__in=animals).values_list('sound', flat=True):
            print('One of the animals in the list makes this sound')
       else:
            print('No animal makes this sound')  

2)如果您使用exists,则更好:

class something:
    animals = [] #type: list[Animals]
    animals = [animal.id for animal in animals]

    def does_atleast_one_animal_make_that_sound(animal_sound):
       if Animal.objects.filter(id__in=animals, sound=animal_sound).exists():
            print('One of the animals in the list makes this sound')
       else:
            print('No animal makes this sound')  

3)如果仅构建(Animal(...))模型,而未将其保存到数据库,则可以使用纯python过滤:

class something:
    animals = [] #type: list[Animals]

   def does_atleast_one_animal_make_that_sound(animal_sound):
       if any(filter(lambda animal: animal.sound == animal_sound, animals)):
            print('One of the animals in the list makes this sound')
       else:
            print('No animal makes this sound')  

注意:通常最好将模型实例过滤委派给数据库(谈论animals变量的起源)。在这种情况下,第三个选项似乎是最好的,因为它不需要查询数据库。