How to register a data matrix in Django

Asked

Viewed 163 times

2

I have an array of data in my Storage Session related to products from a store, and would like to register a sale as soon as the user registers all their products and click Finish Sale.

This matrix of products will earn a line every new product registration in my sale.

How do I take this Séssion Storage and write to my database?

1 answer

2


How’s that product listing? Since it is a data list, you should use bulk_create for this:

#se sua listagem for um dict

produtos = request.session['produtos']
lista = []
for produto in produtos:
     lista.append(Produto(nome=produto['nome'], valor=produto['valor']))

Produto.objects.bulk_create(lista)

This will optimize the creation time. If there are 100 products to be created, it assembles the list and creates everything at once, instead of creating one by one.

  • Cool! This listing is an array, there is a form that I save the products in it, I thought I would have to use AJAX to fetch the Storage Session.

  • The section I referred to above is the one of John himself. You have to see how he is storing his products and send it in the request to save. Not necessarily you will take the products this way, but to save, it is interesting that use bulk_create

  • Oh yes, I’m having a hard time getting this matrix to Django, I think I’ll have to use this very session that he creates and not the browser Section. You recommend something to me to do this?

  • You can add this product to the list by ajax and at the time of the post, take this complete listing or create a js event for your form’s Ubmit to pick up and send this data.

  • Okay, entedi! The bulk_create will not have problems with the foreign key?

  • No, it serves to optimize this process of creating the same type of object. If you have a Foreignkey in your model, just assemble your list with it: lista.append(Product(name=product['name'], valor=product['value'], user=request.user))

  • Okay, thank you! I will do here and confirm your answer :D

  • 1

    See: https://docs.djangoproject.com/en/1.8/ref/models/querysets/#Bulk-create

  • Just one more question, I create my product form by view or with pure HTML?

Show 5 more comments

Browser other questions tagged

You are not signed in. Login or sign up in order to post.