Django 中的 User 和 UserProfile 对象
我在 UserProfile 模型中与 User 相关的字段遇到一些问题。
我的 UserProfile 模型中有这个字段:
friends = models.ManyToManyField(User, null=True)
当我打电话时,
User.objects.get(pk=234).get_profile().friends.all()
我得到一组朋友作为 User 对象
当我打电话时,
User.objects.get(pk=234).friends_set.all()
我得到 UserProfile 对象的列表。
有没有一种方法(无需更改与 UserProfile 对象的关系)可以将关系的每一方作为 User 或 UserProfile 返回?
编辑:
抱歉造成混乱,我想出了我想要做什么:
user = User.objects.get(pk=234)
User.objects.filter(userprofile__friends=user).all()
I'm having some trouble with a related field to User in my UserProfile model.
I have this field in my UserProfile model:
friends = models.ManyToManyField(User, null=True)
When I call
User.objects.get(pk=234).get_profile().friends.all()
I get the set of friends as User objects
When I call
User.objects.get(pk=234).friends_set.all()
I get a list of UserProfile objects.
Is there a way (without changing the relationship to be with a UserProfile object) to get each side of the relationship returned as either User or UserProfile?
EDIT:
Sorry for the confusion i figured out what i was trying to do:
user = User.objects.get(pk=234)
User.objects.filter(userprofile__friends=user).all()
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
我相信这是选择与给定用户为好友的
UserProfile
对象的方法:以下是同一组用户的
User
对象:I believe that this is the way to select the
UserProfile
objects which are friends with a given user:And here are the
User
objects for the same set of users:关系不只是一种,因此不仅仅是您正在考虑的两个方面。一个用户与一个配置文件对象 (FK) 建立关系,另一个用户与多个用户对象 (M2M) 建立关系。
There isn't just one relationship so there is more then just the two sides you are considering. A user has a relationship with a profile object (FK) and another with numerous user objects (M2M).