Django - Models + A list of dictionaries
I have a data structure th开发者_开发知识库at looks like this
[{'name': 'sfsdf sdfsdf', 'id': '621205528'},
{'name': 'test name', 'id': '32324234234'},
{'name': 'another name', 'id': '3434535342221'}]
Now I have a model called Profile where the id in the dictionary maps to the uid field in the model.
I'd like to remove every entry in the list that exists in the database. Is there a elegant way of doing this, right now I have a bunch of for loops that have multiple calls to the db but that may not be the best way to do it.
You could get a matching list from the db in one go, and compare:
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]
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)
This is how I would do it:
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()
A more fleshed-out version:
ids = [x['id'] for x in data] # gives you ['621205528', '32324234234', '3434535342221']
selection = Profile.objects.filter(id__in=ids)
selection.delete()
First you want to get the list of ids from that model in a list
id_list = Profile.objects.filter(whaterever filter).values_list('id', flat=True).order_by('id')
This will return a list if integers.
Then eliminate that from your current list:
mylist = [{'name': 'sfsdf sdfsdf', 'id': '621205528'}, {'name': 'test name', 'id': '32324234234'}, {'name': 'another name', 'id': '3434535342221'}]
for counter, tmp in enumerate (mylist):
if int(tmp['id']) in id_list:
id_list.pop(counter)
if you use pop, it will modify your existing list. If you don't want to alter the existing list, you can create another list as well.
Assuming there are not hundreds of records to delete, you can use the below.
objs = [{'name': 'sfsdf sdfsdf', 'id': '621205528'}, ...]
Profile.objects.filter(id__in=[x.get('id') for x in objs]).delete()
精彩评论