模板中ManyToMany Through模型的Django访问条目

时间:2018-06-26 21:14:43

标签: django django-models django-templates django-views django-orm

我想访问已订阅给定培训的用户列表,我设法获得了具有正确订阅者数量的列表,但是所有订阅都具有当前登录用户的名称。在此先感谢您!

models.py

class Training(Base):
    subscribers = ManyToManyField(User, through = 'Subscription')

class Subscription(Base):
    user = ForeignKey(User, on_delete = CASCADE)
    training = ForeignKey(Training, on_delete = CASCADE)

views.py

class ShowSubscribers(Subscription):
    def get(self):
        self.subscribers = models.Subscription.objects.filter(training = self.get_training())

在我的模板中,我通过以下方式调用列表:

{% for s in subscribers %}
      {{subscription.user.first_name}}
{% endfor %}

1 个答案:

答案 0 :(得分:0)

模板中的subscription是什么?尝试更改此内容:

{% for s in subscribers %}
      {{subscription.user.first_name}}
{% endfor %}

对此:

{% for s in subscribers %}
      {{s.user.first_name}}
{% endfor %}