簡體   English   中英

Peewee,Python,獲取列外鍵中的數據

[英]Peewee, Python, get data in column foreign key

嗨,我有一個數據庫和2個表,

color: color_id | color_name | color_type
fruit: fruit_id | color | fruit_name

我在水果表中的“顏色”是一個外鍵,拖到顏色表中的“ color_id”。

因此,我想用Peewee和Python在水果表中獲取“顏色”,但我總是收到“無”的顏色。

fruits= Fruit.select() 
for fruit in fruits:    
     c = fruit.color   
     print(c)

我嘗試過

fruits = Fruit.get()

但是在這里我不能重復它。 我給你看我的模特:

class Fruit(BaseModel):
    fruit_id= CharField()
    name = Charfield()
    color= ForeignKeyField(column_name='color', field='color', model=Color, null=True)

    class Meta:
        table_name = 'fruit'

您是否知道如何在“水果”表的“顏色”列中獲取值? 謝謝

刪除“ field =“參數,因為這不是必需的,並且僅當需要在相關模型上引用特定(非主鍵)字段時才應指定:

class Fruit(BaseModel):
    fruit_id = CharField()
    name = Charfield()
    color = ForeignKeyField(Color, column_name='color', null=True)

    class Meta:
        table_name = 'fruit

僅供參考,遍歷水果訪問顏色是O(n)查詢的示例。 您最好這樣做,它會連接到顏色表並選擇除水果列之外的顏色列:

query = Fruit.select(Fruit, Color).join(Color)
for fruit in query:
    print(fruit.name, fruit.color.color_name)

暫無
暫無

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

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