是否可以通过字典列表过滤Django对象?

问题描述 投票:0回答:1

假设我有一个 django 对象的查询集,即

Blog
,其中包含字段
id
hits
title
,以及代表这些对象的字典列表:

blog_list = [{'id': 1, 'hits': 30, 'title': 'cat'}, {'id': 2, 'hits': 50, 'title': 'dog'}, {'id': 3, 'hits': 30, 'title': 'cow'}]

其中一个 django 对象的值与字典列表中指定的值不同。 例如,我有一个带有

id = 1
hits = 30
的博客实例,但是
title = 'new cat'

现在我是:

for blog in queryset:
    for entry in blog_list:
        if blog.id == entry['id'] and blog.title != entry['title']:
            print(f'It is the blog entry with id {blog.id}')

但它看起来不太理想而且太复杂。有没有聪明的方法来找到这样的物体?

UPD: @JohnSG 给了我一个有趣的想法,所以现在我这样做了:

for blog in queryset:
    if {'id': blog.id, 'hits': blog.hits, 'title': blog.title} not in blog_list:
        print(f'{blog.id} is missing')

python django orm
1个回答
0
投票

对我来说,这样的事情将是最直接的解决方案:

for dct in blog_list:
    try:
        obj = queryset.get(**dct) 
        print(f"I contain object with {obj.id}")
    except YourModel.DoesNotExist:
        print(f"I did not contain an object with {dct['id']}"
© www.soinside.com 2019 - 2024. All rights reserved.