If you are not sure if the things in your item_list already exist in your database and you need model objects, then get_or_create is definitely the way to go.
If you know that the elements are NOT in your database, you would do much better:
for item in item_list: new = Entry.objects.create( field1 = item.field1, field2 = item.field2, )
And if you don't need objects, just ignore the return from the function call. This will not speed up the DB database, but it will help in memory management if this is a problem.
If you are not sure that the data is already in the database, but there is a unique=True flag in this field, then the database will ensure uniqueness, and you can just catch the exception and move on. This will prevent the addition of an additional database, avoiding trying to select an existing object.
from django.db import IntegrityError for item in item_list: try: new = Entry.objects.create( field1 = item.field1, field2 = item.field2, ) except IntegrityError: continue
You can increase the speed anyway by manually managing transactions. Django will automatically create and complete a transaction for each save, but will provide some decorators that will significantly increase efficiency if you know that you will make many database backups in a specific function. In Django docs, it's better to explain all of this than here, but you probably want to pay special attention to django.db.transaction. commit_on_success
Paul McLanahan Feb 12 2018-10-12 15:42
source share