假设我有一个 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')
对我来说,这样的事情将是最直接的解决方案:
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']}"