【问题标题】:How to save multiple objects from a script in django shell如何从 django shell 中的脚本保存多个对象
【发布时间】:2021-05-02 20:30:30
【问题描述】:

你好同事我想知道这个对象列表是否可以从我展示的脚本中保存,我想从 django shell 执行它

python3 manage.py shell < script.py

以下是我的脚本

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()

它显示给我的错误

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

【问题讨论】:

    标签: python django shell


    【解决方案1】:

    那是因为您将产品包装在一个字符串中。试试这种方式(不围绕产品引用):

    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()
    

    【讨论】:

    • 成功了!非常感谢朋友
    • @AldoMatus 如果是这样,你能接受我或威廉的回答吗?
    【解决方案2】:

    您在单引号之间写了<b>'</b>Products()<b>'</b>,因此作为string,而不是作为Product 对象。

    此外,您最好使用.bulk_create(…) [Django-doc] 而不是手动保存每个对象,因为这将在单个查询中完成:

    从 orders_management.models 导入产品

    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)

    注意:通常 Django 模型被赋予一个单数名称,所以Product而不是Products

    【讨论】:

    • 成功了!非常感谢Willem Van Onsem 的朋友
    猜你喜欢
    • 1970-01-01
    • 2013-04-18
    • 2021-01-10
    • 2020-10-08
    • 1970-01-01
    • 2017-04-22
    • 1970-01-01
    • 1970-01-01
    • 2012-01-11
    相关资源
    最近更新 更多