【问题标题】:Django : how to use modified queryset in templates without saving modificationDjango:如何在模板中使用修改后的查询集而不保存修改
【发布时间】:2019-12-19 03:32:51
【问题描述】:

在我的views.py中,我这样做了:

context_data = {}
all_answers = Answer.objects.all()

for i in range(0, len(all_answers)) :
    all_answers[i].text = modify_text(all_answers[i].text, request)

context_data ["all_answers"] = all_answers 
print(context_data ["all_answers"][0].text) #Check that it was modified

return render(request, 'template.html', context_data)

在我的模板中,我喜欢:

{% for answer in all_answers.all %}
   {{ answer.text}}
{% endfor %}

检查显示已进行修改,但它是我的模板 answer.text 是数据库中未修改的数据。

我看到 context_data ["all_answers"] 的类型是一个查询集,我猜是在模板渲染期间触发的,使任何未保存的更改无用,如何使我的更改显示在模板中?

我试过了:

context_data ["all_answers"] = list(all_answers) 

加载查询集。检查有效,但模板中没有任何显示 (1)

当我使用this function 将查询集加载到字典列表中时,在模板渲染期间出现错误。

我还看到了一个[没有答案的链接问题]。3

我不想保存更改,因为它们是针对每个请求定制的(基本上是针对每个用户)。

** TLDR:如何在不将更改保存到数据库的情况下查看我在模板中的修改?**

PS:使用 Python 3.6.8、Django 2.2.3。

【问题讨论】:

    标签: python django python-3.x


    【解决方案1】:

    查询集不是数据持有者,它们只是惰性引用,并在运行时进行评估。您的代码的问题是您正在修改查询集中的实例(这也是错误的方式,您应该使用in 运算符进行迭代)。

    for answer in all_answers:
        answer.text = modify_text(answer.text, request)
    

    真正的问题是您再次在模板中的查询集上调用all 方法all_answers.all,它返回一个新的查询集并且您没有进行任何更改,因此您应该在模板中这样做

    {% for answer in all_answers %}
       {{ answer.text}}
    {% endfor %}
    

    【讨论】:

      【解决方案2】:

      在 Python 中,您永远不应该遍历 range(len(something)),而应该始终遍历事物本身。对于 Django 查询集,这一点更为重要,因为通过索引 ([i]) 访问未评估查询集中的项目实际上每次都会导致对数据库的单独请求。

      改为这样做:

      for answer in all_answers:
          answer.text = modify_text(answer.text, request)
      
      context_data ["all_answers"] = all_answers 
      print(context_data ["all_answers"][0].text) #Check that it was modified
      

      请注意,循环会评估查询集,因此那里的 [0] 不会导致另一个数据库请求。

      【讨论】:

      • 我以为 Python 中的“for-in”循环没有修改对象的内容?喜欢:a = [1,2,3] for i in a : i = i + 1 print(a) #[1, 2, 3] 。感谢数据库请求的精确性,这肯定是要保留的介意!
      • 当然,但你没有这样做; answer 是对项目的引用,您可以修改其中一个属性。
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2011-01-30
      • 2013-05-11
      • 2023-04-09
      • 1970-01-01
      • 2021-11-18
      • 2016-01-03
      • 2013-04-15
      相关资源
      最近更新 更多