python - How to save list of objects in django models? -
i have list of objects generated after function, want saved in django model 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)
creating new instances of model documented - see creating objects
but explicitly anwser question - 1 solution loop on list of tuples, pass appropriate keyword arguments model class , phone call save(). lastly bit important, otherwise there 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 utilize convenience create() function models manager - don't need phone 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 2 equivalent - matter of preference.
on side note, there naming convention in python should follow when creating classes - "class names should utilize capwords convention." - see pep-8 guidelines
class mymodel(models.model): ... python django
No comments:
Post a Comment