Django 中的 User 和 UserProfile 对象

发布于 2025-01-05 19:20:41 字数 615 浏览 0 评论 0原文

我在 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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

微暖i 2025-01-12 19:20:41

我相信这是选择与给定用户为好友的 UserProfile 对象的方法:

UserProfile.objects.filter(friends__user = 234)

以下是同一组用户的 User 对象:

User.objects.filter(userprofile__friends__user = 234)

I believe that this is the way to select the UserProfile objects which are friends with a given user:

UserProfile.objects.filter(friends__user = 234)

And here are the User objects for the same set of users:

User.objects.filter(userprofile__friends__user = 234)
诗酒趁年少 2025-01-12 19:20:41

关系不只是一种,因此不仅仅是您正在考虑的两个方面。一个用户与一个配置文件对象 (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).

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文