Django查询返回一个模型作为另一个模型

时间:2019-01-19 20:22:16

标签: python django

我找不到类似的问题(也许是因为我不知道正确的用法),但这是我的难题。我有两个模型,一个显示另一个的关系。

我希望能够比较html模板中的“ user_list”和“ friends_list”,以便可以确定是否存在好友关系的情况下是否在“可用用户”部分中不显示用户。

但是,“ user_list”对象属于CustomUser模型类型,而“ friends_list”对象属于Friend模型类型。如何返回get_friends()方法的结果,以便可以从“ user_list”查询集中排除这些朋友(最好是pk),这样我就不必担心字符串比较了?

谢谢!

Models.py

class CustomUserModel(AbstractBaseUser, PermissionsMixin):
    # Simplified for brevity
    username = models.CharFiend(_('username'), unique=True)

class Friend(models.Model):
    user1 = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete.models.CASCADE, related_name='user1')
    user2 = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete.models.CASCADE, related_name='user2')

    objects = FriendManager()

    class Meta:
        unique_together = ('user1', 'user2')

    def __str__(self):
        return str(self.user2)

Managers.py

class FriendManager(models.Manager):
    def is_friend(self, user1, user2):
        if not user1 or not user2:
            return False
        return super(FriendManager, self).get_queryset().filter(user1=user1).filter(user2=user2).exists()

    def get_friends(self, user):
        return super(FriendManager, self).get_queryset().filter(user1=user)

Views.py

class UserList(ListView):
    model = get_user_model()
    context_object_name = "object_list"
    template_name = "users.html"

    def dispatch(self, request, *args, **kwargs):
        self.user = get_user(request)
        return super(UserList, self).dispatch(request, *args, **kwargs)

    def get_queryset(self):
        return get_user_model().objects.order_by("-date_joined")

    def get_friends(self):
        if self.user:
            return Friend.objects.get_friends(self.user).order_by("user2")
        return None

    def get(self, request, *args, **kwargs):
        return render(request, self.template_name, {
            'user_list': self.get_queryset(),
            'friends_list': self.get_friends(),
            'user': self.user
        })

Users.html

{% extends 'base.html' %}
{% block content %}
<h1>Available Users</h1>
{% for user in user_list %}
    {% if user not in friends_list %} <!-- This is my pain-point -->
        <p>{{ user }}</p>
    {% endif %}
{% endfor %}

<h1>Friends</h1>
{% for friend in friends_list %}
    <p>{{ friend }}</p>
{% endfor %}
{% endblock content %}

1 个答案:

答案 0 :(得分:1)

您只需更改查询即可获得CustomUser。因此查询应该类似于CustomeUser.objects.filter(user2__user1=self.user),这将为您提供与CustomUser成为朋友的self.user。根据您对关系的解释方式,还需要查询CustomUser.objects.filter(user1__user2=self.user)。这些查询应替换您视图的get_friends()方法中的查询。