Peewee,Python,获取列外键中的数据

Peewee, Python, get data in column foreign key

嗨,我有一个数据库和 2 tables,

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

我在水果的table中的'color'是一个外键拖到颜色的table中的'color_id'。

所以,有了 Peewee & Python,我想在水果的 table 中得到 'color',但我总是收到 'None'。

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'

您知道如何在我的 table 'fruit' 中获取列 'color' 中的值吗?谢谢

删除 "field=" 参数,因为它不是必需的,只有在需要引用相关模型上的特定(非主键)字段时才应指定:

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

    class Meta:
        table_name = 'fruit

仅供参考,迭代水果 访问颜色是 O(n) 查询的示例。你最好这样做,加入颜色 table 并选择除了水果列之外的颜色列:

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