Python sqlalchemy 模块,ForeignKey() 实例源码

我们从Python开源项目中,提取了以下50个代码示例,用于说明如何使用sqlalchemy.ForeignKey()

项目:zipline-chinese    作者:zhanghan1990    | 项目源码 | 文件源码
def _futures_root_symbols_schema(metadata):
    # NOTE: When modifying this schema, update the ASSET_DB_VERSION value
    return sa.Table(
        'futures_root_symbols',
        metadata,
        sa.Column(
            'root_symbol',
            sa.Text,
            unique=True,
            nullable=False,
            primary_key=True,
        ),
        sa.Column('root_symbol_id', sa.Integer),
        sa.Column('sector', sa.Text),
        sa.Column('description', sa.Text),
        sa.Column(
            'exchange',
            sa.Text,
            sa.ForeignKey('futures_exchanges.exchange'),
        ),
    )
项目:FRG-Crowdsourcing    作者:97amarnathk    | 项目源码 | 文件源码
def upgrade():
    op.create_table(
        'project_stats',
        sa.Column('id', sa.Integer, primary_key=True),
        sa.Column('project_id', sa.Integer, sa.ForeignKey('project.id',
                                                          ondelete='CASCADE')),
        sa.Column('n_tasks', sa.Integer, default=0),
        sa.Column('n_task_runs', sa.Integer, default=0),
        sa.Column('n_results', sa.Integer, default=0),
        sa.Column('n_volunteers', sa.Integer, default=0),
        sa.Column('n_completed_tasks', sa.Integer, default=0),
        sa.Column('overall_progress', sa.Integer, default=0),
        sa.Column('average_time', sa.Float, default=0),
        sa.Column('n_blogposts', sa.Integer, default=0),
        sa.Column('last_activity', sa.Text, default=make_timestamp),
        sa.Column('info', JSON, nullable=False)
    )
项目:fuel-plugin-dns-updater    作者:openstack    | 项目源码 | 文件源码
def init_tables():
    db_instance = Table("instance", dbmeta,
          Column("id", Integer, primary_key=True),
          Column("ip", String(20)),
          Column("name", String(90)),
          Column("uuid", String(40)),
          Column("state", String(90)),
          Column("dns_domain", String(90)),
          Column("created_at", DateTime),
          Column("updated_at", DateTime),
          Column("deleted_at", DateTime)
    )
    db_event = Table("event", dbmeta,
          #will be used for synchronization
          Column("id", Integer, primary_key=True),
          Column("fk_instance_id", Integer, ForeignKey("instance.id")),
          Column("type", String(24)),#enum
          Column("description", String(90)),
          Column("date", DateTime)
    )
    dbmeta.drop_all(dbengine)
    dbmeta.create_all(dbengine)
项目:xiaodi    作者:shenaishiren    | 项目源码 | 文件源码
def _init_cls(cls):
    setattr(cls, '__tablename__', cls.__name__)
    setattr(cls, 'id', Column(Integer, primary_key=True, autoincrement=True))
    for _str in getattr(cls, 'stringV', []):
        setattr(cls, _str, Column(String(DB_STRING_LENGTH)))
    for _int in getattr(cls, 'integerV', []):
        setattr(cls, _int, Column(Integer))
    for _bool in getattr(cls, 'boolV', []):
        setattr(cls, _bool, Column(Boolean))
    for _float in getattr(cls, 'floatV', []):
        setattr(cls, _float, Column(Float))
    for _time in getattr(cls, 'timeV', []):
        setattr(cls, _time, Column(DateTime, default=datetime.utcnow))
    for key, value in getattr(cls, 'foreignKeyV', {}).iteritems():
        setattr(cls, key, Column(Integer, ForeignKey(value), primary_key=True))
    setattr(cls, 'to_json', _convert_attr_to_dict)
项目:aiorchestra-persistence    作者:aiorchestra    | 项目源码 | 文件源码
def upgrade():

    op.create_table(
        'context',
        sa.Column('name', sa.String(), nullable=False, unique=True, primary_key=True),
        sa.Column('status', sa.String(), nullable=False),
        sa.Column('template_path', sa.String(), nullable=False),
        sa.Column('inputs', sa.Text(), nullable=False),
    )
    op.create_table(
        'node',
        sa.Column('context', sa.String(), sa.ForeignKey('context.name'), ),
        sa.Column('name', sa.String(), nullable=False, unique=True),
        sa.Column('is_provisioned', sa.Boolean(), nullable=False),
        sa.Column('properties', sa.Text(), nullable=True),
        sa.Column('attributes', sa.Text(), nullable=True),
        sa.Column('runtime_properties', sa.Text(), nullable=True),
    )
项目:sqlacodegen    作者:agronholm    | 项目源码 | 文件源码
def test_foreign_key_options(self):
        Table(
            'simple_items', self.metadata,
            Column('name', VARCHAR, ForeignKey('simple_items.name', ondelete='CASCADE', onupdate='CASCADE',
                                               deferrable=True, initially='DEFERRED'))
        )

        assert self.generate_code() == """\
# coding: utf-8
from sqlalchemy import Column, ForeignKey, MetaData, String, Table

metadata = MetaData()


t_simple_items = Table(
    'simple_items', metadata,
    Column('name', String, ForeignKey('simple_items.name', ondelete='CASCADE', onupdate='CASCADE', \
deferrable=True, initially='DEFERRED'))
)
"""
项目:town-council    作者:Data4Democracy    | 项目源码 | 文件源码
def get_document():
    _, metadata = setup_db()
    catalog = get_catalog()
    place = get_place()
    event = get_event()

    table = Table(
            'document',
            metadata,
            Column('id', Integer, primary_key=True),
            Column('place_id', Integer, ForeignKey(place.c.id),
                   nullable=False, index=True),
            Column('event_id', Integer, ForeignKey(event.c.id),
                   nullable=False, index=True),
            Column('catalog_id', Integer, ForeignKey(catalog.c.id),
                   nullable=True, index=True),
            Column('url', String),
            Column('url_hash', String),
            Column('media_type', String),
            Column('category', String),
            Column('created_at', DateTime, default=datetime.datetime.now)
    )

    return table
项目:town-council    作者:Data4Democracy    | 项目源码 | 文件源码
def get_event():
    _, metadata = setup_db()
    place = get_place()

    table = Table(
        'event',
        metadata,
        Column('id', Integer, primary_key=True),
        Column('place_id', Integer, ForeignKey(place.c.id),
               nullable=False, index=True),
        Column('name', String),
        Column('scraped_datetime', DateTime, default=datetime.datetime.now),
        Column('record_date', Date),
        Column('source', String),
        Column('source_url', String),
        Column('meeting_type', String)
        )

    return table
项目:GenomicsSampleAPIs    作者:Intel-HLS    | 项目源码 | 文件源码
def upgrade():
    op.create_table(
        'reference',
        sa.Column('id', sa.BigInteger, primary_key=True),
        sa.Column('guid', sa.String(36), nullable=False, unique=True),
        sa.Column('length', sa.BigInteger),
        sa.Column('reference_set_id', sa.BigInteger,
                  sa.ForeignKey('reference_set.id'), nullable=False),
        sa.Column('md5_checksum', sa.String(32)),
        sa.Column('name', sa.Text),
        sa.Column('source_uri', sa.Text),
        sa.Column('is_derived', sa.Boolean),
        sa.Column('source_divergence', sa.Float),
        sa.Column('ncbi_taxon_id', sa.Integer),
        sa.Column('offset', sa.BigInteger)
    )
项目:vcf2db    作者:quinlan-lab    | 项目源码 | 文件源码
def create_expanded(self):
        """
        We store the sample fields, e.g. depths and genotypes in a serialized
        blob but the user can also request --expand [] to have these put into
        separate tables for easier genotype-based querying
        """
        for field in self.expand:
            sql_type = GT_TYPE_LOOKUP[field]
            name = "sample_%s" % field
            cols = [sql.Column('variant_id', sql.Integer,
                               sql.ForeignKey('variants.variant_id'),
                               nullable=False, primary_key=False)]
            cols.extend([sql.Column("sample_" + s, sql_type, index=True) for s in self.samples])
            t = sql.Table(name, self.metadata, *cols)
            t.drop(self.engine, checkfirst=True)
            t.create()
项目:websauna    作者:websauna    | 项目源码 | 文件源码
def gen_relation_models():

    Base = declarative_base()

    class RelationTestModel(Base):
        __tablename__ = "sanity_check_test_2"
        id = Column(Integer, primary_key=True)


    class RelationTestModel2(Base):
        __tablename__ = "sanity_check_test_3"
        id = Column(Integer, primary_key=True)

        test_relationship_id = Column(ForeignKey("sanity_check_test_2.id"))
        test_relationship = relationship(RelationTestModel, primaryjoin=test_relationship_id == RelationTestModel.id)

    return Base, RelationTestModel, RelationTestModel2
项目:reahl    作者:reahl    | 项目源码 | 文件源码
def session_scoped(cls):
    cls.user_session_id = Column(Integer, ForeignKey('usersession.id', ondelete='CASCADE'), index=True)
    cls.user_session = relationship('UserSession', cascade='all, delete')

    @classmethod
    def for_current_session(cls, **kwargs):
        user_session = ExecutionContext.get_context().session
        return cls.for_session(user_session, **kwargs)
    cls.for_current_session = for_current_session

    @classmethod
    def for_session(cls, user_session, **kwargs):
        found = Session.query(cls).filter_by(user_session=user_session)
        if found.count() >= 1:
            return found.one()
        instance = cls(user_session=user_session, **kwargs)
        Session.add(instance)
        return instance
    cls.for_session = for_session

    return cls
项目:reahl    作者:reahl    | 项目源码 | 文件源码
def test_uniqueness_of_request_keys(sql_alchemy_fixture, party_account_fixture):
    fixture = party_account_fixture

    system_account = fixture.new_system_account(activated=False)

    @stubclass(VerificationRequest)
    class VerificationRequestStub(VerificationRequest):
        __tablename__ = 'verificationrequeststub'
        __mapper_args__ = {'polymorphic_identity': 'verificationrequeststub'}
        id = Column(Integer, ForeignKey(VerificationRequest.id), primary_key=True)

        def generate_salt(self):
            self.salt = 'not unique'

    with sql_alchemy_fixture.persistent_test_classes(VerificationRequestStub):
        request1 = VerificationRequestStub()
        Session.add(request1)
        request2 = VerificationRequestStub()
        Session.add(request2)
        clashing_request = VerificationRequestStub()
        Session.add(clashing_request)
        assert request1.as_secret_key() != clashing_request.as_secret_key()
        assert request2.as_secret_key() != clashing_request.as_secret_key()
项目:gnocchi    作者:gnocchixyz    | 项目源码 | 文件源码
def revision(cls):
        tablename_compact = cls.__tablename__
        if tablename_compact.endswith("_history"):
            tablename_compact = tablename_compact[:-6]
        return sqlalchemy.Column(
            sqlalchemy.Integer,
            sqlalchemy.ForeignKey(
                'resource_history.revision',
                ondelete="CASCADE",
                name="fk_%s_revision_rh_revision"
                % tablename_compact,
                # NOTE(sileht): We use to ensure that postgresql
                # does not use AccessExclusiveLock on destination table
                use_alter=True),
            primary_key=True
        )
项目:hreftoday    作者:soasme    | 项目源码 | 文件源码
def upgrade():
    op.create_table(
        'role',
        sa.Column('id', sa.Integer(), nullable=False),
        sa.Column('name', sa.String(length=50)),
        sa.PrimaryKeyConstraint('id'),
        sa.UniqueConstraint('name', name='ux_role_name'),
    )

    op.create_table(
        'user_roles',
        sa.Column('id', sa.Integer(), nullable=False),
        sa.Column('user_id', sa.Integer(), sa.ForeignKey('user.id', ondelete='CASCADE')),
        sa.Column('role_id', sa.Integer(), sa.ForeignKey('role.id', ondelete='CASCADE')),
        sa.PrimaryKeyConstraint('id'),
    )
项目:deb-python-sqlalchemy-utils    作者:openstack    | 项目源码 | 文件源码
def test_with_mapper_and_column_property(self, session, Base, Article):
        class Apple(Base):
            __tablename__ = 'apple'
            id = sa.Column(sa.Integer, primary_key=True)
            article_id = sa.Column(sa.Integer, sa.ForeignKey(Article.id))

        Article.apples = sa.orm.relationship(Apple)

        Article.apple_count = sa.orm.column_property(
            sa.select([sa.func.count(Apple.id)])
            .where(Apple.article_id == Article.id)
            .correlate(Article.__table__)
            .label('apple_count'),
            deferred=True
        )
        query = (
            session.query(sa.inspect(Article))
            .outerjoin(Article.apples)
            .options(
                sa.orm.undefer(Article.apple_count)
            )
            .options(sa.orm.contains_eager(Article.apples))
        )
        query = sort_query(query, 'apple_count')
        assert 'ORDER BY apple_count' in str(query)
项目:deb-python-sqlalchemy-utils    作者:openstack    | 项目源码 | 文件源码
def friendship_tbl(Base):
    return sa.Table(
        'friendships',
        Base.metadata,
        sa.Column(
            'friend_a_id',
            sa.Integer,
            sa.ForeignKey('user.id'),
            primary_key=True
        ),
        sa.Column(
            'friend_b_id',
            sa.Integer,
            sa.ForeignKey('user.id'),
            primary_key=True
        )
    )
项目:deb-python-sqlalchemy-utils    作者:openstack    | 项目源码 | 文件源码
def Comment(Base, Article, User):
    class Comment(Base):
        __tablename__ = 'comment'
        id = sa.Column(sa.Integer, primary_key=True)
        content = sa.Column(sa.String)
        article_id = sa.Column(sa.Integer, sa.ForeignKey(Article.id))
        article = sa.orm.relationship(Article, backref='comments')

        author_id = sa.Column(sa.Integer, sa.ForeignKey(User.id))
        author = sa.orm.relationship(User, backref='comments')

    Article.comment_count = sa.orm.column_property(
        sa.select([sa.func.count(Comment.id)])
        .where(Comment.article_id == Article.id)
        .correlate_except(Article)
    )

    return Comment
项目:deb-python-sqlalchemy-utils    作者:openstack    | 项目源码 | 文件源码
def Article(self, Base, User, Category):
        class Article(Base):
            __tablename__ = 'article'
            id = sa.Column(sa.Integer, primary_key=True)
            name = sa.Column(sa.Unicode(255))
            author_id = sa.Column(
                sa.Integer, sa.ForeignKey(User.id), index=True
            )
            category_id = sa.Column(sa.Integer, sa.ForeignKey(Category.id))

            category = sa.orm.relationship(
                Category,
                primaryjoin=category_id == Category.id,
                backref=sa.orm.backref(
                    'articles',
                )
            )
        return Article
项目:deb-python-sqlalchemy-utils    作者:openstack    | 项目源码 | 文件源码
def TextItem(self, Base, Category):
        class TextItem(Base):
            __tablename__ = 'text_item'
            id = sa.Column(sa.Integer, primary_key=True)
            name = sa.Column(sa.Unicode(255))
            category_id = sa.Column(
                sa.Integer,
                sa.ForeignKey(Category.id)
            )
            category = sa.orm.relationship(
                Category,
                backref=sa.orm.backref(
                    'articles'
                )
            )
            type = sa.Column(sa.Unicode(255))

            __mapper_args__ = {
                'polymorphic_on': type,
            }
        return TextItem
项目:deb-python-sqlalchemy-utils    作者:openstack    | 项目源码 | 文件源码
def SalesInvoice(Base):
    class SalesInvoice(Base):
        __tablename__ = 'sales_invoice'
        id = sa.Column(sa.Integer, primary_key=True)
        order_id = sa.Column(
            'order',
            sa.ForeignKey('order.id'),
            nullable=False
        )
        order = sa.orm.relationship(
            'Order',
            backref=sa.orm.backref(
                'invoice',
                uselist=False
            )
        )
        device_name = sa.Column(sa.String)

        @observes('order.device')
        def process_device(self, device):
            self.device_name = device.name

    return SalesInvoice
项目:deb-python-sqlalchemy-utils    作者:openstack    | 项目源码 | 文件源码
def tagging_tbl(Base):
    return sa.Table(
        'tagging',
        Base.metadata,
        sa.Column(
            'tag_id',
            sa.Integer,
            sa.ForeignKey('tag.id', ondelete='cascade'),
            primary_key=True
        ),
        sa.Column(
            'entry_id',
            sa.Integer,
            sa.ForeignKey('entry.id', ondelete='cascade'),
            primary_key=True
        )
    )
项目:deb-python-sqlalchemy-utils    作者:openstack    | 项目源码 | 文件源码
def User(Base):
    user_group = sa.Table(
        'user_group',
        Base.metadata,
        sa.Column('user_id', sa.Integer, sa.ForeignKey('user.id')),
        sa.Column('group_id', sa.Integer, sa.ForeignKey('group.id'))
    )

    class User(Base):
        __tablename__ = 'user'
        id = sa.Column(sa.Integer, primary_key=True)
        name = sa.Column(sa.Unicode(255))

        @aggregated('groups', sa.Column(sa.Integer, default=0))
        def group_count(self):
            return sa.func.count('1')

        groups = sa.orm.relationship(
            'Group',
            backref='users',
            secondary=user_group
        )
    return User
项目:zipline-chinese    作者:zhanghan1990    | 项目源码 | 文件源码
def _futures_contracts_schema(metadata):
    # NOTE: When modifying this schema, update the ASSET_DB_VERSION value
    return sa.Table(
        'futures_contracts',
        metadata,
        sa.Column(
            'sid',
            sa.Integer,
            unique=True,
            nullable=False,
            primary_key=True,
        ),
        sa.Column('symbol', sa.Text, unique=True, index=True),
        sa.Column(
            'root_symbol',
            sa.Text,
            sa.ForeignKey('futures_root_symbols.root_symbol'),
            index=True
        ),
        sa.Column('asset_name', sa.Text),
        sa.Column('start_date', sa.Integer, default=0, nullable=False),
        sa.Column('end_date', sa.Integer, nullable=False),
        sa.Column('first_traded', sa.Integer, nullable=False),
        sa.Column(
            'exchange',
            sa.Text,
            sa.ForeignKey('futures_exchanges.exchange'),
        ),
        sa.Column('notice_date', sa.Integer, nullable=False),
        sa.Column('expiration_date', sa.Integer, nullable=False),
        sa.Column('auto_close_date', sa.Integer, nullable=False),
        sa.Column('multiplier', sa.Float),
        sa.Column('tick_size', sa.Float),
    )
项目:tasker    作者:DominikPott    | 项目源码 | 文件源码
def task_association_id(cls):
        return Column(Integer, ForeignKey('task_association.id'))
项目:FRG-Crowdsourcing    作者:97amarnathk    | 项目源码 | 文件源码
def upgrade():
    op.create_table('counter',
                    sa.Column('id', sa.Integer, primary_key=True),
                    sa.Column('created', TIMESTAMP),
                    sa.Column('project_id', sa.Integer, 
                              sa.ForeignKey('project.id',
                                            ondelete='CASCADE'),
                              nullable=False),
                    sa.Column('task_id', sa.Integer,
                              sa.ForeignKey('task.id',
                                            ondelete='CASCADE'),
                              nullable=False),
                    sa.Column('n_task_runs', sa.Integer,
                              default=0, nullable=False),
                    )
项目:FRG-Crowdsourcing    作者:97amarnathk    | 项目源码 | 文件源码
def upgrade():
    op.create_table(
        'announcement',
        sa.Column('id', sa.Integer, primary_key=True),
        sa.Column('title', sa.Unicode(length=255), nullable=False),
        sa.Column('body', sa.UnicodeText, nullable=False),
        sa.Column('user_id', sa.Integer, sa.ForeignKey('user.id')),
        sa.Column('created', sa.Text, default=make_timestamp),
    )
项目:FRG-Crowdsourcing    作者:97amarnathk    | 项目源码 | 文件源码
def downgrade():
    op.create_table(
        'featured',
        sa.Column('id', sa.Integer, primary_key=True),
        sa.Column('created', sa.Text, default=make_timestamp),
        sa.Column('app_id', sa.Integer, sa.ForeignKey('app.id'), unique=True)
    )
    query = 'INSERT INTO "featured" (app_id) SELECT id FROM "app" WHERE featured=true;'
    op.execute(query)
    op.drop_column('app', 'featured')
项目:FRG-Crowdsourcing    作者:97amarnathk    | 项目源码 | 文件源码
def upgrade():
    op.create_table(
        'featured',
        sa.Column('id', sa.Integer, primary_key=True),
        sa.Column('created', sa.Text, default=make_timestamp),
        sa.Column('app_id', sa.Integer, ForeignKey('app.id'), unique=True)
    )
项目:FRG-Crowdsourcing    作者:97amarnathk    | 项目源码 | 文件源码
def upgrade():
    op.create_table(
        'result',
        sa.Column('id', sa.Integer, primary_key=True),
        sa.Column('created', sa.Text, default=make_timestamp),
        sa.Column('project_id', sa.Integer, sa.ForeignKey('project.id'), nullable=False),
        sa.Column('task_id', sa.Integer, sa.ForeignKey('task.id'), nullable=False),
        sa.Column('task_run_ids', ARRAY(sa.Integer), nullable=False),
        sa.Column('last_version', sa.Boolean, default=True),
        sa.Column('info', JSON)
    )
项目:FRG-Crowdsourcing    作者:97amarnathk    | 项目源码 | 文件源码
def upgrade():
    op.create_table(
    'blogpost',
    sa.Column('id', sa.Integer, primary_key=True),
    sa.Column('title', sa.Unicode(length=255), nullable=False),
    sa.Column('body', sa.UnicodeText, nullable=False),
    sa.Column('app_id', sa.Integer, sa.ForeignKey('app.id', ondelete='CASCADE'), nullable=False),
    sa.Column('user_id', sa.Integer, sa.ForeignKey('user.id')),
    sa.Column('created', sa.Text, default=make_timestamp),
    )
项目:FRG-Crowdsourcing    作者:97amarnathk    | 项目源码 | 文件源码
def upgrade():
    op.add_column('app', sa.Column(field, sa.Integer, sa.ForeignKey('category.id')))
    # Assign First Category to Published Apps but not draft
    query = 'UPDATE app SET category_id=1 FROM task WHERE app.info LIKE(\'%task_presenter%\') AND task.app_id=app.id AND app.hidden=0'
    op.execute(query)
项目:FRG-Crowdsourcing    作者:97amarnathk    | 项目源码 | 文件源码
def upgrade():
    op.create_table('helpingmaterial',
                    sa.Column('id', sa.Integer,
                              primary_key=True),
                    sa.Column('project_id', sa.Integer,
                              sa.ForeignKey('project.id',
                                            ondelete='CASCADE'),
                              nullable=False),
                    sa.Column('created', TIMESTAMP,
                              default=make_timestamp),
                    sa.Column('info', JSON, nullable=False),
                    sa.Column('media_url', sa.Text),
                    )
项目:bit    作者:codesmart-co    | 项目源码 | 文件源码
def ad_id(cls):
        return Column(Integer, ForeignKey('bit_facebook_ad.id'))

    # Back relation from Ad To DailyAdInsight (Children)
项目:sqlalchemy_bulk_lazy_loader    作者:operator    | 项目源码 | 文件源码
def define_tables(cls, metadata):
        Table(
            'multi_pk', metadata,
            Column("id1", Integer, primary_key=True),
            Column("id2", Integer, primary_key=True),
        )

        Table(
            "multi_fk", metadata,
            Column("id", Integer, primary_key=True),
            Column('multi_pk_id1', Integer),
            Column('multi_pk_id2', Integer),
            ForeignKeyConstraint(['multi_pk_id1', 'multi_pk_id2'], ['multi_pk.id1', 'multi_pk.id2'])
        )

        Table(
            'a', metadata,
            Column("id", Integer, primary_key=True),
        )

        Table(
            'b', metadata,
            Column("id", Integer, primary_key=True),
        )

        Table(
            'a_to_b', metadata,
            Column('a_id', None, ForeignKey('a.id')),
            Column('b_id', None, ForeignKey('b.id')),
        )
项目:sqlalchemy_bulk_lazy_loader    作者:operator    | 项目源码 | 文件源码
def define_tables(cls, metadata):
        Table('users', metadata,
              Column('id', Integer, primary_key=True,
                     test_needs_autoincrement=True),
              Column('name', String(30), nullable=False),
              Column('parent_id', None, ForeignKey('users.id')),
              test_needs_acid=True,
              test_needs_fk=True)

        Table('user_infos', metadata,
              Column('id', Integer, primary_key=True,
                     test_needs_autoincrement=True),
              Column('details', Text),
              Column('user_id', None, ForeignKey('users.id')),
              test_needs_acid=True,
              test_needs_fk=True)

        Table('addresses', metadata,
              Column('id', Integer, primary_key=True,
                     test_needs_autoincrement=True),
              Column('user_id', None, ForeignKey('users.id')),
              Column('email_address', String(50), nullable=False),
              test_needs_acid=True,
              test_needs_fk=True)

        Table('things', metadata,
              Column('id', Integer, primary_key=True,
                     test_needs_autoincrement=True),
              Column('name', String(30), nullable=False),
              test_needs_acid=True,
              test_needs_fk=True)

        Table('user_to_things', metadata,
              Column('user_id', None, ForeignKey('users.id')),
              Column('thing_id', None, ForeignKey('things.id')),
              test_needs_acid=True,
              test_needs_fk=True)
项目:anormbookmarker    作者:jakeogh    | 项目源码 | 文件源码
def __new__(cls, mapper_to_bookmark, mapper_to_bookmark_placeholder=False):
        future_class_attr = {}
        future_class_attr['id'] = Column(Integer, primary_key=True)
        future_class_attr['tag_rel'] = relationship("Tag",
                                                    secondary=lambda: tagbookmarks_table,
                                                    collection_class=set,
                                                    backref=backref('bookmarks'))
        future_class_attr['tags'] = association_proxy('tag_rel', 'tag')

        target_class_name = mapper_to_bookmark.__name__
        target_name = target_class_name.lower().split('.')[-1] # 'filename' usually
        future_class_attr[target_name+'_id'] = Column(Integer, ForeignKey(target_name+'.id'), unique=False, nullable=False)
        future_class_attr[target_name] = relationship(target_class_name, backref='bookmarks')
        future_class_attr['target_class_name'] = target_class_name
        future_class_attr['target_name'] = target_name

        if mapper_to_bookmark_placeholder:
            target_class_name_placeholder = mapper_to_bookmark_placeholder.__name__
            target_name_placeholder = target_class_name_placeholder.lower().split('.')[-1] # byteoffset in the filename case
            future_class_attr[target_name_placeholder+'_id'] = Column(Integer, ForeignKey(target_name_placeholder+'.id'), unique=False, nullable=True)
            future_class_attr[target_name_placeholder] = relationship(target_class_name_placeholder, backref='bookmarks')
            future_class_attr['target_class_name_placeholder'] = target_class_name_placeholder
            future_class_attr['target_name_placeholder'] = target_name_placeholder

        future_class_attr['construct'] = construct
        future_class_attr['__repr__'] = bookmark_repr
        return type('Bookmark', (BASE,), future_class_attr)
项目:pyuniprot    作者:cebel    | 项目源码 | 文件源码
def foreign_key_to(table_name):
    """Creates a standard foreign key to a table in the database

    :param table_name: name of the table without TABLE_PREFIX
    :type table_name: str
    :return: foreign key column 
    :rtype: sqlalchemy.Column
    """
    foreign_column = TABLE_PREFIX + table_name + '.id'
    return Column(Integer, ForeignKey(foreign_column))
项目:pyuniprot    作者:cebel    | 项目源码 | 文件源码
def get_many2many_table(table1, table2):
    table_name = ('{}{}__{}'.format(TABLE_PREFIX, table1, table2))
    return Table(table_name, Base.metadata,
                 Column('{}_id'.format(table1), Integer, ForeignKey('{}{}.id'.format(TABLE_PREFIX, table1))),
                 Column('{}_id'.format(table2), Integer, ForeignKey('{}{}.id'.format(TABLE_PREFIX, table2)))
                 )
项目:flasky    作者:RoseOu    | 项目源码 | 文件源码
def _ensure_table_for_fk(self, metadata, fk):
        """create a placeholder Table object for the referent of a
        ForeignKey.

        """
        if isinstance(fk._colspec, string_types):
            table_key, cname = fk._colspec.rsplit('.', 1)
            sname, tname = self._parse_table_key(table_key)
            if table_key not in metadata.tables:
                rel_t = sa_schema.Table(tname, metadata, schema=sname)
            else:
                rel_t = metadata.tables[table_key]
            if cname not in rel_t.c:
                rel_t.append_column(sa_schema.Column(cname, NULLTYPE))
项目:kuberdock-platform    作者:cloudlinux    | 项目源码 | 文件源码
def downgrade():
    conn = op.get_bind()
    op.add_column('predefined_apps', sa.Column(
        'user_id',
        sa.Integer,
        sa.ForeignKey('users.id'),
        nullable=False,
        server_default='1'))
    op.drop_column('pods', 'template_plan_name')
    op.drop_constraint('resource_role_name_unique', 'rbac_permission')
    op.drop_column('system_settings', 'setting_group')
项目:myreco    作者:dutradda    | 项目源码 | 文件源码
def store_id(cls):
        return sa.Column(sa.ForeignKey('stores.id'), nullable=False)
项目:myreco    作者:dutradda    | 项目源码 | 文件源码
def placement_hash(cls):
        return sa.Column(sa.ForeignKey('placements.hash', ondelete='CASCADE', onupdate='CASCADE'), nullable=False)
项目:myreco    作者:dutradda    | 项目源码 | 文件源码
def variation_id(cls):
        return sa.Column(sa.ForeignKey('variations.id'), nullable=False)
项目:myreco    作者:dutradda    | 项目源码 | 文件源码
def build_variations_slots_table(metadata, **kwargs):
    return sa.Table(
        'variations_slots', metadata,
        sa.Column('variation_id', sa.Integer, sa.ForeignKey('variations.id', ondelete='CASCADE', onupdate='CASCADE'), primary_key=True),
        sa.Column('slot_id', sa.Integer, sa.ForeignKey('slots.id', ondelete='CASCADE', onupdate='CASCADE'), primary_key=True),
        **kwargs)
项目:myreco    作者:dutradda    | 项目源码 | 文件源码
def build_item_types_stores_table(metadata, **kwargs):
    return sa.Table(
        'item_types_stores', metadata,
        sa.Column('item_type_id', sa.Integer, sa.ForeignKey('item_types.id', ondelete='CASCADE', onupdate='CASCADE'), primary_key=True),
        sa.Column('store_id', sa.Integer, sa.ForeignKey('stores.id', ondelete='CASCADE', onupdate='CASCADE'), primary_key=True),
        **kwargs)
项目:myreco    作者:dutradda    | 项目源码 | 文件源码
def method_id(cls):
        return sa.Column(sa.ForeignKey('methods.id'))
项目:myreco    作者:dutradda    | 项目源码 | 文件源码
def build_users_grants_table(metadata, **kwargs):
    return sa.Table(
        'users_grants', metadata,
        sa.Column('user_id', sa.String(255), sa.ForeignKey('users.id', ondelete='CASCADE', onupdate='CASCADE'), primary_key=True),
        sa.Column('grant_id', sa.Integer, sa.ForeignKey('grants.id', ondelete='CASCADE', onupdate='CASCADE'), primary_key=True),
        **kwargs)
项目:myreco    作者:dutradda    | 项目源码 | 文件源码
def build_users_stores_table(metadata, **kwargs):
    return sa.Table(
        'users_stores', metadata,
        sa.Column('user_id', sa.String(255), sa.ForeignKey('users.id', ondelete='CASCADE', onupdate='CASCADE'), primary_key=True),
        sa.Column('store_id', sa.Integer, sa.ForeignKey('stores.id', ondelete='CASCADE', onupdate='CASCADE'), primary_key=True),
        **kwargs)
项目:myreco    作者:dutradda    | 项目源码 | 文件源码
def strategy_id(cls):
        return sa.Column(sa.ForeignKey('engine_strategies.id'), nullable=False)