簡體   English   中英

使用Peewee ORM獲取外鍵字段

[英]Get the foreign key field using Peewee ORM

我試圖使用Peewee ORM選擇一些數據,但是我對如何正確使用外鍵感到困惑。

我想通過Act.id(行為中的默認主鍵)選擇post_title,user_name,act_title。

所以我用這個

Post.select(Post.post_tile,User.user_name,Act.act_title).join(Act).join(User).where(Act.id==actId)

但是我得到了這個:[{“ post_title”:null,“ user”:{},“ act”:{}}]

這是我的模型:

class User(BaseModel):
    user_name = CharField(max_length=30,unique=True) 
    user_email = CharField(max_length=60,unique=True) 

class Act(BaseModel):
    user = ForeignKeyField(User, related_name='users_act_id') #foreignkey
    act_title = CharField(max_length=30)

class Post(BaseModel):
    act = ForeignKeyField(Act,related_name='acts_id') #foreignkey
    user = ForeignKeyField(User,related_name='users_post_id') #foreignkey 
    post_title = CharField(max_length=30)

如果要同時將“用戶”表和“行為”表連接到“發布”表上,則需要在查詢中放置一個開關 ,這樣就可以

Post.select(Post.post_tile,User.user_name,Act.act_title).join(Act).switch(Post).join(User).where(Act.id==actId)

盡管可能不是您想要的結果,因為在Act和Post模型中都將用戶作為外鍵

我認為您唯一缺少的是不查找聯接實例上的值:

posts = (Post
         .select(Post.post_tile,User.user_name,Act.act_title)
         .join(Act)
         .switch(Post)
         .join(User)
         .where(Act.id==actId))
for post in posts:
    print post.post_title, post.user.user_name, post.act.act_title

如果希望將所有屬性全部分配給post對象,則只需添加對.naive()的調用即可,例如:

posts = (Post.select()...where(Act.id==actId).naive())

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM