Home > database >  create new objects from list only if its not in django database
create new objects from list only if its not in django database

Time:12-06

I am having a list of python objects.

suppose py_objs_list = [...data...] Model is Card

I want to create a new object in django database only if database already dont have object

My solution is to do objects.all() on my Card and run a for loop on py_objs_list and check if py_obj in objects.all(). If not present im taking that py_obj into seperate list. Finally creating objects using bulk_create

py_objs_list = [...data...]
cards = list(Card.objects.al()) <--- i know db hits here --->

emails = [card.email for card in cards] <--- does db hit here also everytime in a loop --->
empty_list = []

for py_obj in py_objs_list:
    if py_obj[some_data] not in emails:
        empty_list.append(py_obj)

---bulk_create---

Is this the best way to tackle this problem? pls tell me if not (want the best one). thnks:)

Now my doubt is does db hit everytime in list comprehension as mentioned above

my solution for this problem

CodePudding user response:

You can use bulk_create and set ignore_conflicts=True

https://docs.djangoproject.com/en/4.1/ref/models/querysets/#bulk-create

This will just ignore any records in the object list that cannot be created becuase they already exist.

CodePudding user response:

I think using get_or_create() would be better for your scenario.

Just run a loop over your original list and use as many fields as you want to make sure that a unique instance is found, like so

py_obj_list = [...data...]

for py_obj in py_obj_list:
        Card.objects.get_or_create(email=py_obj.email)

  • Related