Aldo Matus
Aldo Matus

Reputation: 29

How to save multiple objects from a script in django shell

Hello colleagues I would like to know if this list of objects can be saved from a script like the one I show, I want to execute it from the django shell

python3 manage.py shell < script.py

the following is my script

from orders_management.models import Products


objects = [
    'Products(name = "destornillador", section = "ferrreteria", price = 35)',
    'Products(name = "balon", section = "deportes", price = 25)',
    'Products(name = "raqueta", section = "deportes", price = 105)',
    'Products(name = "muneca", section = "juguetes", price = 15)',
    'Products(name = "tren electrico", section = "jugueteria", price = 135)',
]

for object in objects:
    my_product = object
    my_product.save()

the error it shows me

  File "<string>", line 15, in <module>
AttributeError: 'str' object has no attribute 'save'

Upvotes: 0

Views: 1494

Answers (2)

willeM_ Van Onsem
willeM_ Van Onsem

Reputation: 476614

You wrote 'Products()' between single quotes, so as a string, not as a Product object.

Furthermore you better use .bulk_create(…) [Django-doc] instead of saving each object manually, since that will do it in a single query:

from orders_management.models import Products

objects = [
    # no '…'
    Products(name = "destornillador", section = "ferrreteria", price = 35),
    Products(name = "balon", section = "deportes", price = 25),
    Products(name = "raqueta", section = "deportes", price = 105),
    Products(name = "muneca", section = "juguetes", price = 15),
    Products(name = "tren electrico", section = "jugueteria", price = 135),
]

Products.objects.bulk_create(objects)

Note: normally a Django model is given a singular name, so Product instead of Products.

Upvotes: 0

user11718531
user11718531

Reputation:

That is because you have products wrapped in a string. Try it this way (without quotations around the products):

objects = [
    Products(name = "destornillador", section = "ferrreteria", price = 35),
    Products(name = "balon", section = "deportes", price = 25),
    Products(name = "raqueta", section = "deportes", price = 105),
    Products(name = "muneca", section = "juguetes", price = 15),
    Products(name = "tren electrico", section = "jugueteria", price = 135),
]

for object in objects:
    my_product = object
    my_product.save()

Upvotes: 1

Related Questions