首页 > 解决方案 > 如何从模型到视图中检索 for 循环(字典)的输出?

问题描述

我有这个模型:

class ModelName(models.Model):
   def my_dict(self):
         for i in range(n):
             …#some code
             context_a = {‘a’: a}
             return context_a

我需要像这样考虑上下文:

from .models import ModelName

class ViewName
    model = ModelName
    template_name = ’template_name.html’

    def context_b(request):
        context_b = ModelName.objects.get(context_a=context_a) #here I want to get context_a as a dictionary and pass it to context_b for further operations. I know that my syntax here is not correct.
        return render(request, self.template_name, context_b)

如果我这样做,我会得到

Method Not Allowed: /

[18/Nov/2018 12:40:34] "GET / HTTP/1.1" 405 0

我想知道如何正确地做到这一点,以及我应该阅读/学习哪些特定资源(文档和/或文章)来理解我的问题。

我将不胜感激任何帮助。

标签: pythondjango

解决方案


我认为您没有在这里继承适当的基于类的视图。您得到的错误是,您正在调用get方法,但您提供的视图不支持该方法。为了简单起见,让我们使用支持获取请求的DetailsView,所以你可以这样尝试:

class YourView(DetailsView):
  template_name = 'template_name.html'
  model = MyModel

  def get_context_data(self, **kwargs):
     context = super(YourView, self).get_context_data(**kwargs)
     context_a = self.object.my_dict()  # here you will get the dictionary from model in view
     # by the way, you can also access the your model object from context via context['object'] and in template via {{ object }}
     return context

并像这样访问模板的字典:

 {% for k, v in object.my_dict.items %}
      {{ k }} - {{ v }}
 {% endfor %}

还有网址

#urls
path('/someview/<int:pk>/', YourView.as_view(), name="your_view"),

推荐阅读