Django create_or_update模型属性命令工作正常,但更新失败

时间:2015-11-04 07:00:53

标签: python django csv django-models django-orm

我正在尝试编写一个CSV帮助程序来读取CSV文件并更新或创建模型中的字段。 create_or_update查询工作正常,但它只是创建不更新。在更改create_or_update以更新它时会引发错误。 CSV帮助程序的代码是:

def insert_books_from_dictionary(data):

    category, created = Category.objects.update_or_create(name=data['category'])
    sub_category = None

    if data['sub_category'].decode('utf-8') != '':
        sub_category, created = SubCategory.objects.update_or_create(name=data['sub_category'], category=category)

    publisher, created = Publisher.objects.update_or_create(name=data['publishers'])
    # convert strings to float

    # ToDo : Fix constraints and create a function
    # to handle data check and conversion
    try:
        price = float(data['mrp_price'])
    except ValueError:
        price = 0.0
        pass

    try:
        pages = float(data['pages'])
    except ValueError:
        pages = None
        pass
    isbn_13_str = str(data['isbn_13'])
    isbn_10_str = str(data['isbn_10'])
    image_url_str = str(data['image_url'])
    binding = 1 if data['binding'] == 'Hardboard' else 2
    book, created = Book.objects.update(title=data['title'],description=data['description'], pages=pages, binding=binding, price=price, category=category,sub_category=sub_category, edition_and_year=data['edition_and_year'],
        isbn_10=isbn_10_str, isbn_13=isbn_13_str,image_url=image_url_str)

    book.publishers.add(publisher)

    authors = re.split(",", data['authors'].decode('utf-8'))
    for author in authors:
        author, created = Author.objects.update_or_create(name=author.strip())

        book.authors.add(author)

    return dict(book_id=book.id)

它会抛出以下错误:

Traceback (most recent call last):
File "common/util/upload.py", line 18, in <module>
uploadbooks = book_upload(old_file, newfile)
File "common/util/upload.py", line 12, in book_upload
insert_seller_books_from_dictionary(req_data)
File "/home/subhajit/textnook/common/util/csv_helper.py", line 132, in    insert_seller_books_from_dictionary
book_id = insert_books_from_dictionary(data)
File "/home/subhajit/textnook/common/util/csv_helper.py", line 167, in insert_books_from_dictionary
isbn_10=isbn_10_str, isbn_13=isbn_13_str,image_url=image_url_str)
TypeError: 'long' object is not iterable

更改更新以创建错误不再是。我该如何解决这个问题?

1 个答案:

答案 0 :(得分:0)

book, created = Book.objects.update(title=data['title'],description=data['description'], pages=pages, binding=binding, price=price, category=category,sub_category=sub_category, edition_and_year=data['edition_and_year'],
            isbn_10=isbn_10_str, isbn_13=isbn_13_str,image_url=image_url_str)

您使用的是update,而不是update_or_create

Book.objects.update仅更新returns the number of rows affected,这是'long' object is not iterable python抱怨的内容,因为它必须将其元素分配给元组book, created

相关问题