Insert a list into a database made with Django

Asked

Viewed 78 times

0

Hello, I want to insert a list of names in a database I created with Django, but I’m not getting it. Is there a method to enter all names at once? (NOTE. I have already performed the makemigrations and migrate commands)

class Usuario(models.Model):
nome = models.CharField(blank=False,max_length = 50)

The list I want to insert is this:

lista = ['André','Carla','João','Maria','Thelma','Ana']
  • Tens Bulk Insert... https://www.caktusgroup.com/blog/2019/01/09/django-bulk-inserts/

3 answers

0

For Bulk Insert, I already shared a link with a possible solution, but it uses a class and at first glance seems more complicated, but simplifying. Here is the solution.

array_objects = []
lista = ['André','Carla','João','Maria','Thelma','Ana']
for nome in lista:
    array_objects.append(Usuario(nome=nome))
Usuario.objects.bulk_create(array_objects)

0

Italo’s response has a number of caveats, such as not working in many relationship to many. See in the documentation, then I put one more option:

from <nome-do-pacote> import Usuario

lista = ['André','Carla','João','Maria','Thelma','Ana']
for nome in lista:
    Usuario.create(nome=nome)

0

Entry.objects.bulk_create([
  Entry(headline='This is a test'),
  Entry(headline='This is only a test'),
])

Only replace with the attribute (headline) you want, in your case nome

Browser other questions tagged

You are not signed in. Login or sign up in order to post.