Django get_context_data,动态内容

时间:2018-08-20 12:46:15

标签: django-templates django-views

我要拉出用户列表,然后为每个用户在“详细信息视图”中拉出特定统计信息。我希望能够只对get_context视图中的数据进行循环,但是我非常误解,然后我将错误进一步移到了模板上,它可以正常工作!是的:/

我认为get_context_data最适合此操作,但是我正在摸索如何更有效地执行此操作的障碍。下面的“我的代码”让我得到了我想要的东西,但它并不漂亮。

usermodel_detail.html

{% for i in range %}
    <h3>Trainees {{trainees|index:forloop.counter0}}</h3>

    {% if foods|index:forloop.counter0 %}
        {% for food in foods|index:forloop.counter0 %}
            .
            .
            .
        {% endfor  %}
    {% endif %}
{% endfor %}

views.py

class UserModelDetailView(LoginRequiredMixin, DetailView):
    model = UserModel

    def get_context_data(self, **kwargs):
        context = super(UserModelDetailView, self).get_context_data(**kwargs)
        context['trainees'] = UserModel.objects.filter(trainer_email=self.request.user)
        foods = dict()
        for index,trainee in enumerate(context['trainees']):
            foods[index] = Food.objects.filter(user_id=trainee.pk)
        context['foods'] = foods
        context['range'] = str(len(context['trainees']) + 10) # had to add 10 to get the range to be 2 strings long, works for now but it's not a good way
        return context

    def get_queryset(self):
        userpk = self.request.user.pk
        queryset = UserModel.objects.filter(pk=userpk)
        return queryset

是否有更简便的方法或更好的方法?

0 个答案:

没有答案