Django与用户的多对多关系

问题描述 投票:0回答:2
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字段,以找出所有用户的状态为“已关注”或与经过身份验证的用户共有。我不想创建循环。就像上面的关注和取消关注一样,我内部是否有检查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 %}

类关系(models.Model):from_user = models.ForeignKey(User,related_name ='from_user')to_user = models.ForeignKey(User,related_name ='to_user')status = models.CharField(...

django django-models django-templates django-views django-related-manager
2个回答
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 %}

0
投票

Inside Views.py

© www.soinside.com 2019 - 2024. All rights reserved.