使用 Peewee 的关系映射
Relational Mapping using Peewee
我是关系数据库的新手,我对如何创建模型感到很困惑。我需要做的是通过语言选择过滤帖子内容,为此我需要创建一个关系数据库。当我决定我应该有多少模型(表)来完成这个时,我的疑问就来了。这是一个例子:
models.py
class Post(Model):
timestamp = DateTimeField(default=datetime.datetime.now)
user = ForeignKeyField(
rel_model=User,
related_name='posts'
)
language = TextField()
content = ForeignKeyField(THIS NEEDS TO POINT TO THE LANGUAGE)
class Meta:
database = DATABASE
有没有可能完成这样的事情?我应该创建多个 Post 模型吗?
先谢谢你。
您 运行 阅读了快速入门指南了吗?这样做可能会让您了解如何创建模型和建立关系:
http://docs.peewee-orm.com/en/latest/peewee/quickstart.html
要回答您的直接问题,您可以为语言创建另一个 table,即
class Language(Model):
name = CharField()
class Meta:
database = DATABASE
所以你将拥有(稍微清理一下):
DATABASE = SqliteDatabase('mydb.db') # or PostgresqlDatabase or MySQLDatabase
class BaseModel(Model):
class Meta:
database = DATABASE
class User(BaseModel):
email = CharField()
# whatever other user fields
class Language(BaseModel):
name = CharField()
# other fields?
class Post(BaseModel):
timestamp = DateTimeField(default=datetime.datetime.now)
user = ForeignKeyField(User, related_name='posts')
language = TextField()
content = ForeignKeyField(Language, related_name='posts')
我是关系数据库的新手,我对如何创建模型感到很困惑。我需要做的是通过语言选择过滤帖子内容,为此我需要创建一个关系数据库。当我决定我应该有多少模型(表)来完成这个时,我的疑问就来了。这是一个例子:
models.py
class Post(Model):
timestamp = DateTimeField(default=datetime.datetime.now)
user = ForeignKeyField(
rel_model=User,
related_name='posts'
)
language = TextField()
content = ForeignKeyField(THIS NEEDS TO POINT TO THE LANGUAGE)
class Meta:
database = DATABASE
有没有可能完成这样的事情?我应该创建多个 Post 模型吗?
先谢谢你。
您 运行 阅读了快速入门指南了吗?这样做可能会让您了解如何创建模型和建立关系:
http://docs.peewee-orm.com/en/latest/peewee/quickstart.html
要回答您的直接问题,您可以为语言创建另一个 table,即
class Language(Model):
name = CharField()
class Meta:
database = DATABASE
所以你将拥有(稍微清理一下):
DATABASE = SqliteDatabase('mydb.db') # or PostgresqlDatabase or MySQLDatabase
class BaseModel(Model):
class Meta:
database = DATABASE
class User(BaseModel):
email = CharField()
# whatever other user fields
class Language(BaseModel):
name = CharField()
# other fields?
class Post(BaseModel):
timestamp = DateTimeField(default=datetime.datetime.now)
user = ForeignKeyField(User, related_name='posts')
language = TextField()
content = ForeignKeyField(Language, related_name='posts')