Skip to main content
 首页 » 编程设计

python之(Python)之Peewee之如何创建外键

2025年05月04日10oomusou

我正在尝试通过外键在两个表字段之间创建关系,但是文档中的示例或 stackoverflow 上的相关线程失败了。这是我的代码:

class User(BaseModel): 
    """ Field Types """ 
    user_id = PrimaryKeyField() 
    username = CharField(25) 
    role = ForeignKeyField(User, to_field='role_id') 
 
    class Meta: 
        db_table = 'users' 
 
 
class User(BaseModel): 
    """ Field Types """ 
    role_id = PrimaryKeyField() 
    rolename = CharField(25) 
 
    class Meta: 
        db_table = 'roles' 

to_field 是指我的代码片段中等效表“users”中的相关字段。在 peewee 的文档中,我看到 related_names 作为参数,它指的是用户模型中不存在的字段 tweets。

class User(Model): 
    name = CharField() 
 
class Tweet(Model): 
    user = ForeignKeyField(User, related_name='tweets') 
    content = TextField() 

希望有人能解释一下这个语法。

请您参考如下方法:

我不认为你想要 2 "User"楷模。和 tweets与你的User无关和 Role模式。

你的意思还不是很清楚,但我认为这样的事情应该可行。

class Role(BaseModel): 
    """ Field Types """ 
    role_id = PrimaryKeyField() 
    rolename = CharField(25) 
 
    class Meta: 
        db_table = 'roles' 
 
class User(BaseModel): 
    """ Field Types """ 
    user_id = PrimaryKeyField() 
    username = CharField(25) 
    role = ForeignKeyField(Role, to_field="role_id") 
 
    class Meta: 
        db_table = 'users' 

希望to_field的意思清楚了。它说,role User 上的字段模型应指向 Role 中的记录基于 role_id 的表格专栏。

相关名称用于反向引用。例如,您可以将它们组合起来,以便您可以访问具有给定角色的所有用户。

例如,更改您的用户类别:

class User(BaseModel): 
    """ Field Types """ 
    user_id = PrimaryKeyField() 
    username = CharField(25) 
    role = ForeignKeyField(Role, to_field="role_id", related_name="users") 
 
    class Meta: 
        db_table = 'users' 

现在您已经有了发言权,加载了“ super 用户”角色,您应该能够执行类似这样的操作来遍历所有具有该角色的用户。

for user in superuser.users 
    print user.username