如何从模型到视图检索for循环(字典)的输出?

时间:2018-11-18 13:39:01

标签: python django

我有这个模型:

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

我想知道如何正确执行操作,以及我应该阅读/学习的特定资源(文档和/或文章)以了解我的问题。

我将不胜感激。

1 个答案:

答案 0 :(得分:0)

我认为您不是在这里将基于类的适当视图归为一类。 您得到的错误是,您正在调用get方法,但是您提供的视图不支持该方法。为了简单起见,让我们使用支持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"),