在Django中获取用户关注的主题?

时间:2018-05-08 09:40:33

标签: python django

我正在开发应用程序,用户可以按照主题获取更新。

以下是models.py

from django.contrib.auth.models import User

class Topic(models.Model):
    name = models.CharField(max_length=30, unique=True)
    description = models.CharField(max_length=300)
    created_on = models.DateTimeField(auto_now_add=True)
    created_by = models.ForeignKey(User, related_name='topic')
    def __str__(self):
        return self.name

class Follow(models.Model):
    topic = models.ForeignKey(Topic, related_name='follow')
    user = models.ForeignKey(User, related_name='follow')

views.py

def home(req):
    user_id = req.user.id
    follow = Follow.objects.filter(user = req.user).all()
    follow = [f.topic for f in follow]
    question = Question.objects.filter(topic__in=follow).all()
    answer = Answer.objects.filter(ques__in=question).all()
    topic = Topic.objects.all().distinct(name)
    return render(req,'home.html',{'topic':topic,'answer':answer,'upvote':upvote})

模板:

            {% for t in topic %}   
                {% for ft in t.follow.all%}
                    {% if ft.user == user %}
                        <h4 id="{{t.pk}}" class="topCls"><span class="badge badge-success">{{t.name}}</span></h4>
                    {% endif %}
                {% endfor %}
            &nbsp;
            {% endfor %}

我需要让用户按照绿色和红色的其他主题使用主题

如上所述,我可以获得用户关注的主题,如何区分跟随与否?

提前致谢!!!

1 个答案:

答案 0 :(得分:2)

您可以检查以下列表中的主题:

{% for t in topic %}   
    {% if t in follow  %}
      <h4 id="{{t.pk}}" class="topCls"><span class="badge badge-success">{{t.name}}</span></h4>
    {% else %
      <h4 id="{{t.pk}}" class="topCls"><span class="badge badge-warning">{{t.name}}</span></h4>
    {% endif %}
&nbsp;
{% endfor %}

您需要将follow列表传递给上下文:

def home(req):
    user_id = req.user.id
    follow = Topic.objects.filter(follow__user=req.user)
    question = Question.objects.filter(topic__in=follow).all()
    answer = Answer.objects.filter(ques__in=question).all()
    topic = Topic.objects.all().distinct(name)
    return render(req,'home.html',{'topic':topic,'answer':answer,'upvote':upvote, 'follow': follow})