Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to save list of objects in django models?

Tags:

python

django

I have a list of objects generated after some function, i want it to be saved in django model i tried query set operation

mylist = [(u'england', u'1', u'cde', u'IMG1', u'CP1'), (u'england', u'1', u'cde', u'IMG2', u'CP1'), (u'england', u'2', u'abc', u'IMG1', u'CP1')] 

class Mymodel(models.Model):
   batch_id = models.AutoField(primary_key=True)
   batch_cola = models.CharField(max_length=100)
   batch_colb = models.CharField(max_length=100)
   batch_colc = models.CharField(max_length=100)
   batch_cold = models.CharField(max_length=100)
   batch_cole = models.CharField(max_length=100)
like image 558
shashisp Avatar asked Jun 24 '14 13:06

shashisp


2 Answers

You can use the bulk_create method - something like:

Mymodel.objects.bulk_create([Mymodel(**{'batch_cola' : m[0],
                                        'batch_colb' : m[1],
                                        'batch_colc' : m[2],
                                        'batch_cold' : m[3],
                                        'batch_cole' : m[4]})
                            for m in mylist])

Instead of iterating over the objects and calling save() on every single one of them, this method results in a single database hit for all the objects, as opposed to one hit for each object.

like image 144
kreld Avatar answered Sep 18 '22 13:09

kreld


Creating new instances of a model are well documented - see creating objects

But to explicitly anwser your question - one solution is to loop over the list of tuples, pass the appropriate keyword arguments to the model class and then call save(). The last bit is important, otherwise there will be no database level transaction.

for t in mylist:
    Mymodel(batch_cola=t[0], batch_colb=t[1],
           batch_colc=t[2], batch_cold=t[3],
           batch_cole=t[4]).save()

You can also use the convenience create() function from the models manager - you don't need to call .save() then.

for t in mylist:
    Mymodel.object.create(batch_cola=t[0], batch_colb=t[1],
           batch_colc=t[2], batch_cold=t[3], batch_cole=t[4])

The docs say that the two are equivalent - so its somewhat a matter of preference.

On a side note, there is a naming convention in Python you should follow when creating Classes - "Class names should normally use the CapWords convention." - see PEP-8 guidelines

class MyModel(models.Model):
    ...
like image 21
dannymilsom Avatar answered Sep 19 '22 13:09

dannymilsom