(Python) - Peewee - 如何创建外键
我正在尝试通过外键在两个表的字段之间建立关系,但根据文档或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的参数,它指的是User模型中并不存在的字段tweets。
class User(Model):
name = CharField()
class Tweet(Model):
user = ForeignKeyField(User, related_name='tweets')
content = TextField()
希望有人能解释一下这个语法。
2 个回答
-1
是不是第二个类 User
class User(BaseModel):
""" Field Types """
role_id = PrimaryKeyField()
rolename = CharField(25)
class Meta:
db_table = 'roles'
应该改成类 Roles 呢?
class Roles(BaseModel):
""" Field Types """
role_id = PrimaryKeyField()
rolename = CharField(25)
class Meta:
db_table = 'roles'
5
我觉得你不应该有两个 "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
的意思能让你明白。它的意思是,User
模型中的 role
字段应该指向 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'
现在假设你已经加载了 "Superuser" 角色,你应该能这样做,遍历所有拥有这个角色的用户。
for user in superuser.users
print user.username