Django 1.7 - SQL - 从关系可能存在或不存在的一对多关系中获取数据
Django 1.7 - SQL - Get data from One-To-Many relationship where relation may or may not exist
我有以下数据库布局,
用户(有一个)User_Profile
User_Profile(没有,一个或多个)World_Profile
World_Profile(有一个)世界
我想要 select 所有 World 对象的列表,如果 world profile 存在 [=33] =]用户 世界简介也。
世界table具有属性is_public。我想获得所有具有 is_public = True 的 World 的列表,或者用户具有 World_Profile[=56 的列表=].
我怀疑它与 select_related 术语有关,但我还没有成功。任何帮助将不胜感激。
表格属性
用户(用户名,first_name,last_name,电子邮件)
User_Profile(用户名(FK->User), info, foo, bar)
World_Profile(user_profile(FK), 世界(FK), character_name, 黄金)
世界(world_name, game_speed, is_public, requires_subscription)
已解决
filter_string = Q(is_public = True) | Q(worldprofile__user_profile__user=user)
World.objects.select_related().filter(filter_string)
经过反复试验找到了解决方案,不确定为什么 worldprofile 不需要下划线,我必须检查一下。谢谢大家
Burhan Khalid 有更好的答案。
用户 = request.user
user.user_profile.world_profile_set.filter(世界__is_public=真)
最简单的部分是获取当前登录的用户,这在 request.user
中可用。由于django提供了反向关系"for free",你可以这样做:
user = request.user
user.user_profile.world_profile_set.filter(world__is_public=True)
filter_string = Q(is_public = True) | Q(worldprofile__user_profile__user=user)
World.objects.select_related().filter(filter_string)
经过多次试验和错误后找到了解决方案,不确定为什么 worldprofile 不需要下划线,我必须检查一下。谢谢大家
我有以下数据库布局,
用户(有一个)User_Profile
User_Profile(没有,一个或多个)World_Profile
World_Profile(有一个)世界
我想要 select 所有 World 对象的列表,如果 world profile 存在 [=33] =]用户 世界简介也。
世界table具有属性is_public。我想获得所有具有 is_public = True 的 World 的列表,或者用户具有 World_Profile[=56 的列表=].
我怀疑它与 select_related 术语有关,但我还没有成功。任何帮助将不胜感激。
表格属性
用户(用户名,first_name,last_name,电子邮件) User_Profile(用户名(FK->User), info, foo, bar) World_Profile(user_profile(FK), 世界(FK), character_name, 黄金) 世界(world_name, game_speed, is_public, requires_subscription)
已解决
filter_string = Q(is_public = True) | Q(worldprofile__user_profile__user=user)
World.objects.select_related().filter(filter_string)
经过反复试验找到了解决方案,不确定为什么 worldprofile 不需要下划线,我必须检查一下。谢谢大家
Burhan Khalid 有更好的答案。 用户 = request.user user.user_profile.world_profile_set.filter(世界__is_public=真)
最简单的部分是获取当前登录的用户,这在 request.user
中可用。由于django提供了反向关系"for free",你可以这样做:
user = request.user
user.user_profile.world_profile_set.filter(world__is_public=True)
filter_string = Q(is_public = True) | Q(worldprofile__user_profile__user=user)
World.objects.select_related().filter(filter_string)
经过多次试验和错误后找到了解决方案,不确定为什么 worldprofile 不需要下划线,我必须检查一下。谢谢大家