简体   繁体   English

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

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

Hi I have a database and 2 tables, 嗨,我有一个数据库和2个表,

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

My 'color' in fruit's table is a foreignkey draging to 'color_id' in color's table. 我在水果表中的“颜色”是一个外键,拖到颜色表中的“ color_id”。

So, with Peewee & Python I want to get 'color' in fruit's table, but I alsways receive a 'None'. 因此,我想用Peewee和Python在水果表中获取“颜色”,但我总是收到“无”的颜色。

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

I tried with 我尝试过

fruits = Fruit.get()

But here I can't iterate with it. 但是在这里我不能重复它。 I show you my model: 我给你看我的模特:

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

    class Meta:
        table_name = 'fruit'

Do you have any idea how I can get the value inside my column 'color' in my table 'fruit' ? 您是否知道如何在“水果”表的“颜色”列中获取值? Thanx 谢谢

Remove the "field=" parameter, as that is not necessary and should only be specified if you need to reference a specific (non-primary-key) field on the related model: 删除“ field =“参数,因为这不是必需的,并且仅当需要在相关模型上引用特定(非主键)字段时才应指定:

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

    class Meta:
        table_name = 'fruit

Just for reference, iterating over fruits and accessing the color is an example of O(n) queries. 仅供参考,遍历水果访问颜色是O(n)查询的示例。 You're better off doing this, which joins on the color table and selects the color columns in addition to the fruit columns: 您最好这样做,它会连接到颜色表并选择除水果列之外的颜色列:

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