0

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'

2 Answers 2

1

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()
Sign up to request clarification or add additional context in comments.

1 Comment

@AldoMatus If that is the case, could you accept my or Williem's answer?
0

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.

1 Comment

IT WORKED! THANKS A LOT FRIEND Willem Van Onsem

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.