[英]django queryset select all from multiple tables
我想 select 使用 django 查詢集從多個表連接所有列對應於以下 sql
select user.*, address.*, contact.* from user left join address on user.id = address.userid left join contact on user.id = contact.userid
我有關注 python
User.objects.values()
獲取所有用戶數據。
User.objects.values(first_name, last_name, contacts__number, addresses__zip)
獲取特定列
但我不知道如何從所有 3 個表中獲取所有列,例如
User.objects.values(*, contacts__*, addressess__*)
如果您已經在User
class 上定義了ForeignKey
關系,您可以使用:
users = User.objects.select_related("Address", "Contact").all()
然后您可以訪問User
object 上的相關 object 作為屬性:
for user in users:
print(user.address)
print(user.contact)
實際上, select_related()
提示不是必需的,您可以在任何情況下將相關記錄作為屬性訪問,它只是防止每次訪問都進行單獨的數據庫查詢。
如果您在 Django auth 應用程序中使用User
model,您可以通過 go 實現您的目標:
Attach a model as the profile to DJango User
model: https://docs.djangoproject.com/en/4.1/topics/auth/customizing/#extending-the-existing-user-model
用您自己的 model 替換默認User
model: https://docs.djangoproject.com/en/4.1/stitutopics/acustom-user-sub/4.1/stitutopics/#-a
使用“反向”關系查詢: https://docs.djangoproject.com/en/4.1/topics/db/queries/#lookups-that-span-relationships
我希望這能解決你的問題。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.