I am using SQLALCHEMY Version 1.2.17
I am using declarative approach to define models, One of my declarative
table definition not available in metadata even i attached the table with
metadata so when other table which is in same metadata is trying to create
relationship with that table it throws the below error:
NoReferencedTableError(u"Foreign key associated with column
'deal_term_rate_options.deal_id' could not find table 'deal.deal' with
which to generate a foreign key to target column 'deal_id'",)
Attaching the required files for reference.
deal_db is db connection
>>> from fni_django_sorcery.db import databases
>>> deal_db = databases.get("Deal")
>>> deal_db
<SQLAlchemy
engine=oracle+cx_oracle://dtadm:***@DT20DB_ORA?allow_twophase=False&coerce_to_decimal=False&optimize_limits=True&use_binds_for_limits=False>
>>> deal_db.metadata
MetaData(bind=None)
>>> deal_db.metadata.tables
immutabledict({})
I don't see any error on console also.
Any help will be appreciated.
--
SQLAlchemy -
The Python SQL Toolkit and Object Relational Mapper
http://www.sqlalchemy.org/
To post example code, please provide an MCVE: Minimal, Complete, and Verifiable
Example. See http://stackoverflow.com/help/mcve for a full description.
---
You received this message because you are subscribed to the Google Groups
"sqlalchemy" group.
To unsubscribe from this group and stop receiving emails from it, send an email
to [email protected].
To view this discussion on the web visit
https://groups.google.com/d/msgid/sqlalchemy/f6cd9899-2f0a-47fc-860f-1740fc4e2ddd%40googlegroups.com.
# -*- coding: utf-8 -*-
"""
Base model
"""
from __future__ import absolute_import, print_function, unicode_literals
import six
from fni_django_sorcery.db.models import serialize
from sqlalchemy.orm import class_mapper
__all__ = ["BaseModel", "BaseModelMixin"]
class BaseModelMixin(object):
@property
def serialize(self):
return serialize(self)
# TODO: Add `columns_not_to_clone` functionality to sorcery's clone so we can use that instead.
def clone(self, columns_not_to_clone, attrs_to_override):
"""
Clone object passed in this context
Args:
columns_not_to_clone(List): List of columns not to clone
attrs_to_override(Dict): Attribute that need to be overridden
Returns:
Cloned object
"""
obj_class = type(self)
mapper = class_mapper(obj_class)
arguments = dict()
if not attrs_to_override:
attrs_to_override = {}
for name, column in mapper.columns.items():
try:
if not (column.primary_key or column.unique) and (name not in columns_not_to_clone):
arguments[name] = getattr(self, name)
except AttributeError:
# certain sqlalchemy virtual column types like column_property
# will not have a `.primary_key` or `.unique` property.
# Just ignore these and do not try to clone.
pass
arguments.update(attrs_to_override)
cloned_obj = obj_class(**arguments)
return cloned_obj
class BaseModel(BaseModelMixin):
"""Base Model for sqlalchemy classes
* __init__ provides a default constructor ala sqlalchemy or django
declarative default constructors.
* __repr__ is class name and primary key(s)
* __str__ uses unicode if it can (we define that more...revisit??)
"""
def __init__(self, **kwargs):
"""Object initialization using keyword arguments
bogus kwargs will generate an error...no extras allowed!
"""
for key, val in kwargs.items():
if hasattr(self.__class__, key):
setattr(self, key, val)
else:
raise TypeError("got unexpected keyword argument %r" % key)
def __repr__(self):
# model, keys = instance_state(self).key
keys = self._sa_class_manager.mapper.primary_key_from_instance(self)
if len(keys) == 1:
key = keys[0]
args = "(%r)" % (str(key) if isinstance(key, six.text_type) else key)
else:
args = repr(tuple(str(x) if isinstance(x, six.text_type) else x for x in keys))
return self.__class__.__name__ + args
def __str__(self):
"""Just try to make `print obj` work interactively."""
return repr(self)
# -*- coding: utf-8 -*-
from __future__ import absolute_import, print_function, unicode_literals
from sqlalchemy.orm import relationship
from sqlalchemy import (
BigInteger,
Column
)
from ..declarative import DeclarativeBase
from .termrateoption import TermRateOption
class Deal(DeclarativeBase):
"""
Deal Model
"""
__tablename__ = "deal"
__table_args__ = {"schema": "deal"}
# primary key
dlr_cd = Column("dlr_cd", BigInteger(), primary_key=True)
deal_jacket_id = Column("deal_jacket_id", BigInteger(), primary_key=True)
deal_id = Column("deal_id", BigInteger(), primary_key=True)
# Relationships
termrateoptions = relationship(TermRateOption, primaryjoin=(deal_id == TermRateOption.deal_id and deal_jacket_id == TermRateOption.deal_jacket_id and dlr_cd == TermRateOption.dlr_cd),
lazy='joined',
cascade="all, delete, delete-orphan")
def __init__(self, deal_id=None, **kwargs):
self.deal_id = deal_id
super(Deal, self).__init__(**kwargs)
# -*- coding: utf-8 -*-
from __future__ import absolute_import, print_function, unicode_literals
from sqlalchemy.ext.declarative import declarative_base
from ..tables.base import metadata
from .base_model import BaseModel
DeclarativeBase = declarative_base(cls=BaseModel, metadata=metadata)
# -*- coding: utf-8 -*-
from __future__ import absolute_import, print_function, unicode_literals
from datetime import datetime # noqa
import sqlalchemy as sa
from core.db import deal_db
from dt_database_utils.db.dt_sql_conventions import register
from dt_database_utils.db.gensequence import * # noqa
from fni_django_sorcery.db.models import autocoerce
from sqlalchemy import * # noqa
from sqlalchemy.orm import * # noqa
from sqlalchemy.types import * # noqa
metadata = register(deal_db.metadata) # noqa
# -*- coding: utf-8 -*-
from __future__ import absolute_import, print_function, unicode_literals
from dt_database_utils.db_wrapper import gensequence
from datetime import datetime
from sqlalchemy import (
BigInteger,
Column,
DateTime,
Integer,
Numeric,
func,
Index,
ForeignKeyConstraint,
SmallInteger
)
from ..declarative import DeclarativeBase
class TermRateOption(DeclarativeBase):
"""
Term Rate Model
"""
__tablename__ = "deal_term_rate_options"
__table_args__ = (
ForeignKeyConstraint(
["dlr_cd", "deal_jacket_id", "deal_id"],
["deal.deal.dlr_cd", "deal.deal.deal_jacket_id", "deal.deal.deal_id"],
name="FK01_DEAL_TERM_RATE_OPTIONS",
use_alter=True
),
{"schema": "menu"},
)
# primary key
deal_term_rate_option_id = Column("deal_term_rate_option_id", BigInteger(), primary_key=True)
# other columns
apr = Column("apr", Numeric(asdecimal=True, precision=8, scale=2))
ballon_payment = Column("ballon_payment", Numeric(asdecimal=True, precision=14, scale=2))
created_ts = Column("created_ts", DateTime(), nullable=False, server_default=func.now(),
default=datetime.utcnow)
deal_id = Column("deal_id", BigInteger(), nullable=False)
deal_jacket_id = Column("deal_jacket_id", BigInteger(), nullable=False)
dlr_cd = Column("dlr_cd", BigInteger(), nullable=False)
money_factor = Column("money_factor", Numeric(asdecimal=True, precision=8, scale=2))
payment = Column("payment", Numeric(asdecimal=True, precision=14, scale=2))
position = Column("position", Integer())
residual = Column("residual", Numeric(asdecimal=True, precision=8, scale=2))
term = Column("term", SmallInteger())
def __init__(self, deal_term_rate_option_id=None, **kwargs):
self.deal_term_rate_option_id = deal_term_rate_option_id or gensequence()
super(TermRateOption, self).__init__(**kwargs)
Index("fx01_deal_term_rate_options", TermRateOption.dlr_cd, TermRateOption.deal_jacket_id,
TermRateOption.deal_id, unique=False)