0
我定義了一些車型的一些關聯表的M2M關係關係表:蒸餾器不檢測
from itsdangerous import TimedJSONWebSignatureSerializer
from passlib.hash import bcrypt
from sqlalchemy.ext.declarative import declarative_base
import app
from app import db
Base = declarative_base()
class UserGroupRelationship(Base):
__tablename__ = 'users_groups'
id = db.Column(db.Integer, primary_key=True)
user_id = db.Column(db.Integer, db.ForeignKey('users.id'), primary_key=True)
group_id = db.Column(db.Integer, db.ForeignKey('groups.id'), primary_key=True)
class FriendRelationship(Base):
__tablename__ = u'users_friends'
id = db.Column(db.Integer, primary_key=True)
user_left = db.Column(db.Integer, db.ForeignKey('users.id'), primary_key=True)
user_right = db.Column(db.Integer, db.ForeignKey('users.id'), primary_key=True)
class User(db.Model):
__tablename__ = u'users'
id = db.Column(db.Integer, primary_key=True)
name = db.Column(db.String(50))
email = db.Column(db.String(120), unique=True)
password = db.Column(db.String(120))
# ...
last_login = db.Column(db.DateTime, default=db.func.now())
friends = db.relationship(FriendRelationship,
primaryjoin=id==FriendRelationship.user_left,
backref='friends', lazy='dynamic')
friends_with = db.relationship(FriendRelationship,
primaryjoin=id==FriendRelationship.user_right,
backref='friends_with', lazy='dynamic')
class Group(db.Model):
__tablename__ = u'groups'
id = db.Column(db.Integer, primary_key=True)
name = db.Column(db.String(50))
users = db.relationship(UserGroupRelationship,
primaryjoin=id==UserGroupRelationship.group_id,
backref='groups', lazy='dynamic')
class Device(db.Model):
''' devices linked to users '''
__tablename__ = u'devices'
id = db.Column(db.Integer, primary_key=True)
name = db.Column(db.String(50))
uuid = db.Column(db.String(50))
date_added = db.Column(db.DateTime)
user_id = db.Column(db.Integer, db.ForeignKey('groups.id'))
運行alembic revision --autogenerate
並生成類從db.Model
繼承表,但不適合用於M2M我的表關係。
INFO [alembic.migration] Context impl PostgresqlImpl.
INFO [alembic.migration] Will assume transactional DDL.
INFO [alembic.autogenerate] Detected added table u'groups'
INFO [alembic.autogenerate] Detected added table u'users'
INFO [alembic.autogenerate] Detected added table u'devices'
INFO [alembic.autogenerate] Detected added table u'question'
Generating /Users/rxdazn/w/xxx/xxx-
yyy/migrations/versions/4e47aa7f3050_.py...done
我alembic.ini
和env.py
文件是默認的。我只是導入我的模型init我的項目的__init__.py
什麼可能會導致此行爲的任何想法?
爲什麼當你的模型繼承'db.Model'時,你從'Base'繼承關聯表?他們都是模特兒,對吧? – Miguel
@Miguel我認爲關係與簡單模型不同。我的意思是我認爲他們不應該成爲模特。繼承'db.Model'似乎解決了我的問題。 您可以創建發佈作爲答案,所以我可以標記我的問題解決?感謝(並感謝您的博客文章!)。 – rxdazn
對於多對多關係有兩種模式。 [基本](http://docs.sqlalchemy.org/en/rel_0_9/orm/relationships.html#many-to-many)爲關聯表使用一個「表」對象。 [advanced](http://docs.sqlalchemy.org/en/rel_0_9/orm/relationships.html#association-object)使用模型,其優點是可以將其他列存儲在關聯表中。你似乎在使用高級的,但是如果你使用的是Flask-SQLAlchemy,那麼你所有的模型應該從'db.Model'繼承,你不應該直接去SQLAlchemy。 – Miguel