Reputation: 29
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
Reputation: 476614
You wrote 'Products()'
between single quotes, so as a str
ing, 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
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