【问题标题】:How to check if value occurs in a field of a model list in Django?如何检查值是否出现在Django模型列表的字段中?
【发布时间】:2018-08-02 22:58:55
【问题描述】:

我有一个 Django 模型列表,我想检查字符串值是否出现在列表中任何模型的特定字段中的某处。请看下面的例子:

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')

如何正确编写带有“...”的函数部分?

【问题讨论】:

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


    【解决方案1】:

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

    1) 查询集的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变量的来源)。在这种情况下,第 3 个选项似乎是最好的,因为它不需要查询数据库。

    【讨论】:

    • 这不是检查我在数据库中的所有模型吗?我想要包括的唯一动物是顶部定义的动物列表中的动物。有没有办法只用那些?例如,假设动物 = [Cow, Chicken],但我的 DB Animal 模型有 [Cow,Chicken,Dog]。在您的函数中,“woof”会返回 true,但我希望“woof”返回 false,因为它不在我的列表中
    猜你喜欢
    • 1970-01-01
    • 2015-08-11
    • 2015-06-20
    • 2015-03-24
    • 1970-01-01
    • 2022-01-03
    • 2021-08-03
    • 2011-11-20
    • 2015-05-31
    相关资源
    最近更新 更多