python - 《flask web 开发》一书,数据库中多对多关系的实现问题?
ringa_lee
ringa_lee 2017-04-18 10:24:21
0
2
585

问题原型是,现在要实现用户之间的互相能够关注的功能,反应到数据库中是一个多对多的关系,书里引入了第三个关联表,模型是这么定义的(用户表是users,主键定义为id):

class Follow(db.Model):
    __tablename__ = 'follows'
    follower_id = db.Column(db.Integer, db.ForeignKey('users.id'),
                            primary_key=True)
    followed_id = db.Column(db.Integer, db.ForeignKey('users.id'),
                            primary_key=True)
    timestamp = db.Column(db.DateTime, default=datetime.utcnow)

Follow表中的每条记录代表着一个user关注另一个user,那么不论是follower_id列还是followed_id列都必然会出现重复。那么:
1.在这种情况下为何还能定义成主键呢?
2.如果不定义成主键会有什么不同?(是不能用了还是性能下降还是什么别的?)

ringa_lee
ringa_lee

ringa_lee

reply all(2)
黄舟

Use Column to define a column. The class name is the name of the variable you assign it to. If you want to use a different name in the table, you can provide a string of the desired column name as the optional first argument. Primary keys are marked with primary_key=Ture. Multiple keys can be marked as primary keys, in which case they serve as composite primary keys.

I saw it in the SQLAlchemy documentation, so the usage here should be a composite primary key.

阿神

A table has only one primary key, and multiple primary keys cannot be set at the same time.
follower_id and followed_id should be set as unique keys, that is, unique key.

Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!