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

Django create_or_update model attribute command works fine but update fails

我正在尝试编写一个 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

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

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