在Django中使用for循环保存多个列值

时间:2019-01-04 14:57:05

标签: django python-3.x django-models django-views

在我的数据库(SQLite)中,我想通过字典的for循环来更新给定行中的每一列。我已经搜索了SO和Django文档,但是无法找到有关通过for循环更新多列的任何信息。我怀疑有一个简单的解决方案可以解决我的问题,但是我用不到Google的关键字。

这是一个非常简单的示例,将问题归结为核心:

models.py

from django.db import models

class author_ratings(models.Model):
    name = models.TextField()
    book_one = models.IntegerField()
    book_two = models.IntegerField()
    book_three = models.IntegerField()

views.py

from models import author_ratings

ratings_dictionary = {'book_one': 10, 'book_two': 20, 'book_three': 30}

current_author = author_ratings.objects.filter(name="Jim")

for book,rating in ratings_dictionary:
    current_author.book = rating
    current_author.save()

问题:Django没有将值10、20和30保存到该作者行的相应列中,而是抛出了以下错误:

“ AttributeError:'current_author'对象没有属性'book'”

编辑: 在下面的答案中,Shafikur Ra​​hman正确指出“ book”不是可用字段(仅“ name”,“ book_one”,“ book_two”和“ book_three”可用)。我的问题变成了:如何使用for循环更新每个字段而不必对所有字段进行硬编码?

例如,我要避免不必显式键入每一列:

current_author.book_one = ratings_dictionary['book_one']
current_author.book_two = ratings_dictionary['book_two']
current_author.book_three = ratings_dictionary['book_three']
current_author.save()

以上信息应足以完全理解该问题,但是我可以根据要求提供任何其他详细信息。 预先感谢您的协助。

3 个答案:

答案 0 :(得分:2)

使用current_author = author_ratings.objects.filter(name="Jim"),您将获得QuerySet,而不是模型的实例。因此,通过

   current_author.book_one = ratings_dictionary['book_one']
   current_author.book_two = ratings_dictionary['book_two']
   current_author.book_three = ratings_dictionary['book_three']
   current_author.save()

您仍然会收到错误消息。至少'QuerySet' object has no attribute 'save'

但是查询集具有update方法,如果您不坚持使用循环,可以节省几行代码:

current_author.update(**ratings_dictionary)是您所需要的

答案 1 :(得分:1)

您的author_ratings模型没有字段book,因此存在错误。可用字段为namebook_onebook_twobook_three

答案 2 :(得分:1)

在views.py中,您可以:

@Override   
public Optional<Integer> getValue() {
    return Optional.empty();
}

您可以阅读有关from models import author_ratings ratings_dictionary = {'book_one': 10, 'book_two': 20, 'book_three': 30} current_author = author_ratings.objects.filter(name="Jim") current_author.update(**ratings_dictionary) in the docs的信息。