简体   繁体   中英

Relational Mapping using Peewee

I'm new to relational databases and I'm quite confused on how should I create the models. What I need need to get done is to filter the posts content through the language choice and to do that I need to create a relational database. My doubt comes when deciding how many models(tables) should I have to accomplish this. Here is an example:

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

Is it possible to accomplish something like this? Should I create more than one Post model?

Thank you in advanced.

Have you run through the quickstart guide? Doing so might give you a feel for how to create models and set up relationships:

http://docs.peewee-orm.com/en/latest/peewee/quickstart.html

To answer your immediate question, you can create another table for language, ie

class Language(Model):
    name = CharField()

    class Meta:
        database = DATABASE

So all together you'd have (cleaned up a bit):

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')

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM