[英]Convert SQL query set into Django Model Query-set
我需要一點幫助,我來自使用關系數據模型,現在我冒險進入 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;
模型已經創建,但我不知道如何在 python 中創建滿足此查詢條件的視圖
基本上,您需要使用select_related來“預加載”關聯,然后您只需使用常規方法來導航它們。
假設您的模型類似於
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]
現在您已加載所有數據(以及更多)
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.