Answer the question
In order to leave comments, you need to log in
Sets of objects in one request (insert/update)?
There is a shop. There are goods coming in a CSV file.
Now I'm iterating over the file line by line. string = item.
If the product is not in the database, then I add it. If there is, then I update the price.
As a result, I get a bunch of requests to add, update. Although, in fact, the data is static and can be stored in a list, and then massively fed into the database with one request. How to do this using the ORM dzhangi methods?
Goal:
Fewer database calls, faster file processing, less hardware load
Now:
file_url = './../file/items.csv'
with open(file_url, 'rb') as csvfile: # перебираем строки
spamreader = csv.reader(csvfile, delimiter='|', quoting=csv.QUOTE_MINIMAL)
for row in spamreader: # перебираем ячейки в строке
id_item = row['item'].replace("'", "")
item = Item.objects.filter(id_item=id_item)
if not item:
item = Item(id_item=id_item)
item.name = row['name'].replace("'", "")
....
else:
item = item[0]
item.price = row['price'].replace("'", "")
item.save()
all_item = Item.objects.all().values_list('id_item', flat=True)
file_url = './../file/items.csv'
add_item = []
upd_item = []
with open(file_url, 'rb') as csvfile:
spamreader = csv.reader(csvfile, delimiter='|', quoting=csv.QUOTE_MINIMAL)
for row in spamreader:
id_item = row['id_item'].replace("'", "")
if id_item in all_item: # Та самая проверка
upd_item.append({'id_item': id_item, 'price': row['price'].replace("'", "")})
else:
add_item.append({'id_item': id_item, 'name': row['name'].replace("'", "")})
# Вот тут уже то самое добавление / обновление
# Item(add_item).save() or Item(upd_item).save()
Answer the question
In order to leave comments, you need to log in
Goal:on the contrary - you need to transfer a maximum to a DB let itself
Fewer database calls, faster file processing, less hardware load
@transaction.atomic
def do_stuff():
# This code executes inside a transaction.
About csv parsing: it's embarrassing to pull replace manually - maybe you need to specify quotechar, or write your own Dialect?
As for create and update, jung now has a wonderful update_or_create .
About your decision - be sure to wrap all_item in the simplest set so that the entry is searched instantly, and not linearly from the number of products! In your case it's just ValuesQuerySet -> list!
As I see it:
1) With one request you get goods from the database
2) You parse the price
3) You compare the lists obtained in steps 1 and 2
4) Based on them, you form lists for adding and updating
5) Using bulk_create or create, you create goods using update you update
6) ...
7) Profit
That is, in fact, as you wrote (if I understand correctly)
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question