[英]Convert SQL query set into Django Model Query-set
I need a little help, I come from working with relational data models and now I venture into Django Framework, I need to make an API that returns something like this SQL query我需要一点帮助,我来自使用关系数据模型,现在我冒险进入 Django 框架,我需要创建一个 API 来返回类似这样的 SQL 查询
SELECT user_profile_userprofile.email,
user_profile_userprofile.name,
business_unity.active AS status,
profile.name AS profile,
business_unity.name AS unit
FROM user_profile_userprofile
JOIN profile ON user_profile_userprofile.id = profile.id
JOIN user_profile_unity ON user_profile_unity.user_id = user_profile_userprofile.id
JOIN business_unity ON user_profile_unity.id = business_unity.id;
The models are already created but I don't know how to make a view in python that meets the conditions of this query模型已经创建,但我不知道如何在 python 中创建满足此查询条件的视图
Basically, you need to "preload" the associations using select_related , and then you just use the normal methods to navigate them.基本上,您需要使用select_related来“预加载”关联,然后您只需使用常规方法来导航它们。
Assuming your models are something like假设您的模型类似于
class UserProfile(Model):
profile = ForeignKey("Profiles", ...)
unity = ForeignKey("Unity", ...)
class Unity(Model):
business_unity = ForeignKey("business.Unity", ...)
qs = UserProfile.select_related("profile", "unity__business_unity").all()
up = qs[0]
Now you have all your data loaded (and more)现在您已加载所有数据(以及更多)
print(up.email)
print(up.name)
print(up.unity.business_unity.active)
print(up.profile.name)
print(up.unity.business_unity.name)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.