我有一个如下所示的数据结构
[{'name': 'sfsdf sdfsdf', 'id': '621205528'},
{'name': 'test name', 'id': '32324234234'},
{'name': 'another name', 'id': '3434535342221'}]现在我有一个名为Profile的模型,其中字典中的id映射到模型中的uid字段。
我想删除列表中存在于数据库中的所有条目。有没有一种优雅的方法来做这件事,现在我有一堆for循环,它们有多个对db的调用,但这可能不是最好的方法。
发布于 2011-07-13 00:11:56
您可以一次性从db中获取匹配列表,然后进行比较:
db_ids = set(Profile.objects.values_list('uid', flat=True))
my_ids = set([d['id'] for d in original_list])
ids_to_keep = my_ids - db_ids
list_to_keep = [l for l in original_list if l['id'] in ids_to_keep]发布于 2011-07-13 00:12:35
ids = [x['id'] for x in my_list]
existing_ids = Profile.objects.filter(id__in=ids).values_list('id', flat=True)
result = filter(lambda elm: elm['id'] in existing_ids, my_list)发布于 2011-07-13 00:10:42
这就是我要做的:
data = [{'name': 'sfsdf sdfsdf', 'id': '621205528'},
{'name': 'test name', 'id': '32324234234'},
{'name': 'another name', 'id': '3434535342221'}]
Profile.objects.filter(id__in=[x['id'] for x in data]).delete()一个更丰富的版本:
ids = [x['id'] for x in data] # gives you ['621205528', '32324234234', '3434535342221']
selection = Profile.objects.filter(id__in=ids)
selection.delete()https://stackoverflow.com/questions/6667210
复制相似问题