简体   繁体   English

Django使用内置的User模型时,如何按名称优雅地过滤Friend对象?

[英]Django How would I filter Friend objects elegantly by name when using the built in User model?

I am learning by building and have a little FriendShip class. 我正在通过构建进行学习,并开设了一些FriendShip课程。 In one of my views, I want to filter the FriendShips such that my user is shown a list of all friendships he or she is involved in. 在我的一种观点中,我想过滤FriendShips,以便向用户显示他或她参与的所有友谊的列表。

To give you an idea, something like this that has valid syntax: 为了给您一个主意,类似以下的内容具有有效的语法:

relevant_friends_list = FriendShip.objects.filter(request.user.username == creator || request.user.username == friend)

But you can't just do that since friend and creator are user objects. 但是,由于朋友和创建者都是用户对象,因此您不能仅仅这样做。

models.py models.py

from django.contrib.auth.models import User
class FriendShip(models.Model):
    created = models.DateTimeField(auto_now_add=True, editable=False)
    creator = models.ForeignKey(User, related_name="friendship_creator_set")
    friend = models.ForeignKey(User, related_name="friend_set")
    def __str__(self):
        return self.creator.username + " | " + self.friend.username

If I were to mimic the tutorial, I would add properties like creator_name = models.charField(...) and set that equal to User.username or something. 如果要模仿本教程,我将添加诸如creator_name = models.charField(...)之类的属性,并将其设置为User.username或其他名称。 But that sounds like I'm overthinking things, and it just feels like django would have a minimal-line solution. 但这听起来像是我想得太多,感觉就像django将提供一个最小的解决方案。 Thanks for your time 谢谢你的时间

You are indeed overthinking. 您的确在思考。 You can filter by model objects, and since you want an OR operation, you can use Q objects like so: 您可以按模型对象进行过滤,并且由于要执行“或”运算,因此可以使用Q对象,如下所示:

from django.db.models import Q

user = request.user
conditions = Q(creator=user) | Q(friend=user)
relevant_friends_list = FriendShip.objects.filter(conditions)

Note that request.user is only available inside a view where the request object is available. 请注意,request.user仅在请求对象可用的视图内可用。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM