Search code examples
pythonflask-peewee

How to create a Object that has PrimaryKeyField and ForeignKeyField ? Python Flask PeeWee


the classes:

class User(flask_db.Model, UserMixin):
    id = PrimaryKeyField()
    social_id = CharField(null=False, unique=True)
    nickname = CharField(null=False)
    email = CharField(null=True)

class Feed(flask_db.Model):
    id = PrimaryKeyField()
    user = ForeignKeyField(User, related_name='feeds')
    title = CharField()
    url = CharField()
    description = CharField()

If I do something like:

newfeed = Feed.create(..)

What should I put in the type id and in the type user ?

How should I get all the feeds of a User ? With something like this ?

    feedsofuserTom = Feed.select().where(Feed.user == userTom)

I don't understand the ForeignKeyField() function, I read the documentation but the examples didn't work for me. http://docs.peewee-orm.com/en/latest/peewee/models.html


Solution

  • ForeignKey is a relation between models. ForeignKey is ManyToOne relation. So for your Feed you can relate as many Users as you want.

    So in your example firstly you have to create User instanse. And then add it while creating Feed. first_user = User.create(social_id=1, nickname=name, email="email") newfeed = Feed.create(user=first_user, title="cool feed", url="url.com", description="description")

    As far as i remember you don't have to add PrimaryKeyField(). This field will be added automatically by database.