How to bulk insert & update data in database using Django

  • 2 days ago
To maximize the performance of my code, I'm trying always to minimize the number of sql queries. In this video, I'm showing just an example in Django how to bulk insert and save data in the database.

Gist url: https://gist.github.com/InterTuts/6c589b466bdfa01ba1d15e48a15f16d7
Transcript
00:00For maximum code efficiency, I aim to minimize SQL requests to the database.
00:10And in this video, I'll show how to bulk insert and update data in a database using Drango.
00:23In my example, I'm using the Facebook API to request all my Facebook pages from my Facebook account.
00:40I could have 200 Facebook pages and I can't save them in the database one by one.
00:59I need a bulk solution.
01:05Before save, I'm using this query to get all my saved Facebook pages from the database.
01:23Then, I need to convert the networks list, which is a query set now, into a list because I need to update it.
01:43Then, I'll extract all Facebook pages saved ID because I'll verify if the Facebook pages were already saved.
02:07If were saved, I'll get the index because I'll use it to update the Facebook page name and access token.
02:30If a Facebook page is not saved, I'll save it in a list.
02:39Then, I'll bulk save that list in the database with this code.
02:48Finally, I'll use this list with updated data to bulk update it in the database.
03:04In this way, with three SQL queries, I can update or save even 200 rows in my database.

Recommended