Djano与User有很多很多关系

时间:2015-08-02 10:28:56

标签: django django-models django-templates django-views django-related-manager

class Relationship(models.Model):
    from_user = models.ForeignKey(User, related_name='from_user')
    to_user = models.ForeignKey(User, related_name='to_user')
    status = models.CharField(max_length=255, choices=RELATIONSHIP_STATUSES)

field = models.ManyToManyField('User', through=Relationship, symmetrical=False, related_name='related_to')
field.contribute_to_class(User, 'relationships')

这样可以正常关注和取消关注

users = User.objects.all()
{%for u in users %}
    {% if not request.user in u.related_to.all %}
          <input type="submit" value="Follow"/>
    {% else %}
          <input type="submit" value="UnFollow"/>
    {% endif %}
{%endfor%}

但我希望使用User对象获取Relationship status字段,以找出所有用户的状态是Follow或与经过身份验证的用户相互关联。 我不想创建循环。像上面的跟随和取消关注我已经检查request.user内部与否,就像我想要检查状态是否相互或跟随

users = User.objects.all()

{% for u in users %}
   // here I want to get the Relationship status field using the User object to find out the status of all user is Following or mutual with authenticated user
{% endfor %}

2 个答案:

答案 0 :(得分:0)

试试这个:我认为这可以帮到你,

{% for u in users %}
    {% for relation in u.relationship_set.all %}
        from: {{ relation.from_user.username }}
        to: {{ relation.to_user.username }}
        status: {{ relation.get_status_display }}
    {% endfor %}
{% endfor %}

同时尝试'from_user'或'to_user'而不是'relationship_set'

答案 1 :(得分:0)

内部Views.py

users = User.objects.all()
mutual = []
for me in members:
    try:
       Relationship.object.get(to_users=me, from_users=request.user,status='Mutual')
       mutual.append(True)
    except Relationship.DoesNotExist:
       mutual.append(False)

内部模板

{% if mutual == True %}
Mutual
{% endif %}

任何更好的主意请建议,因为上面的代码运行每个用户的查询。对于许多查询