Python Forum
sqlalchemy could not find table
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
sqlalchemy could not find table
#1
Hi!
Please help me with the error below.
I also tried with the command: user_id = Column (String (13), ForeignKey ('users.user_id')) without child and parent as I used below.

Error:
raise exc.NoReferencedTableError( sqlalchemy.exc.NoReferencedTableError: Foreign key associated with column 'userstransactions.transaction_id' could not find table 'users' with which to generate a foreign key to target column 'user_id'
repository -> userstransactions.py
from sqlalchemy.orm import sessionmaker
from Model.Domain.users_transactions import UsersTransactions

from Utils.utils import Base, engine


class DBUsersTransactionsRepository:
    def __init__(self):
        self.session = sessionmaker(engine)()

    # CREATE
    def add_transactions(self, transaction_id, user_id, currency, amount, vendor, date_time):
        new_transaction = UsersTransactions(
            transaction_id=transaction_id,
            user_id=user_id,
            currency=currency,
            amount=amount,
            vendor=vendor,
            date_time=date_time
        )

        self.session.add(new_transaction)
        self.session.commit()

if __name__ == '__main__':
    Base.metadata.create_all(engine)
    depo_repo = DBUsersTransactionsRepository()

    depo_repo.add_transactions(
        transaction_id=123,
        user_id='1234',
        currency='EUR',
        vendor='Altex',
        date_time='2022-01-02'
    )
    depo_repo.add_transactions(
        transaction_id=124,
        user_id='1235',
        currency='EUR',
        vendor='EMAG',
        date_time='2022-04-02'
    )
    depo_repo.add_transactions(
        transaction_id=125,
        user_id='1234',
        currency='USD',
        vendor='EMAG',
        date_time='2022-03-02'
    )
domain -> userstransaction.py
from sqlalchemy import Column, String, Integer, Float, ForeignKey
from sqlalchemy.types import DateTime

from Utils.utils import Base


class UsersTransactions(Base):
    __tablename__ = 'userstransactions'

    transaction_id = Column(Integer, ForeignKey('users.user_id'), primary_key=True)
    user_id = Column(String(13))
    currency = Column(String(3), ForeignKey('currencies.currency', ondelete='CASCADE'))
    amount = Column(Float(2), nullable=False)
    vendor = Column(String(100), nullable=False)
    date_time = Column(DateTime, nullable=False)
    parent_id = Column(String, ForeignKey('users.user_id'))

    def __repr__(self):
        return f'{self.transactions_id}, {self.user_id}, {self.currency}, {self.amount}, {self.vendor}, {self.date_time}'
domain -> users.py
from sqlalchemy import Column, String
from sqlalchemy.orm import relationship
from sqlalchemy.types import Date, DateTime

from Utils.utils import Base


class Users(Base):
    __tablename__ = 'users'

    user_id = Column(String(13), primary_key=True)
    first_name = Column(String(30), nullable=False)
    last_name = Column(String(30), nullable=False)
    email_name = Column(String(50), nullable=False)
    address = Column(String(50), nullable=False)
    phone_number = Column(String(10), nullable=False)
    date_of_birth = Column(Date, nullable=False)
    join_date = Column(DateTime, nullable=False)
    children = relationship('UsersTransactions')

    def __repr__(self):
        return f'user id = {self.user_id}\n' \
               f'first name = {self.first_name}\n' \
               f'last name = {self.last_name}\n' \
               f'email = {self.email_name}\n' \
               f'phone = {self.phone_number}\n' \
               f'date of birth = {self.date_of_birth}\n' \
               f'join date = {self.join_date}'
Reply
#2
Please show your directory structure so I can run model.
Reply
#3
Photo 
(Mar-29-2022, 07:57 PM)Larz60+ Wrote: Please show your directory structure so I can run model.

I attached photo

Attached Files

Thumbnail(s)
   
Reply
#4
just got up, I'll take a look at this first thing after coffee

Starting now (7:18 EDT) get back ASAP.
Reply
#5
There are files (not presented) that are needed to create database, such as base.py and engine.py
I don't want copies as they may be sensitive.
Instead, here is a model for one table only that I know is correct (part of my tutorial here: https://python-forum.io/thread-24127.html )

DatabaseModel.py
from sqlalchemy import (
    Column,
    String,
    Integer,
    Date,
    create_engine,
    DateTime,
    ForeignKey,
)
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy.orm import relationship, backref
from datetime import datetime
from SqlPaths import SqlPaths
 
 
spath = SqlPaths()
engine = create_engine(f"sqlite:///{spath.sample_db}")
Base = declarative_base()
 
 
class ConnecticutCity(Base):
 
    __tablename__ = "ConnecticutCity"
 
    id = Column(Integer, primary_key=True)
 
    TownName = Column(String(40), index=True, unique=True)
    County = Column(String(40), index=True)
    YearEstablished = Column(String(10), index=True)
    ParentTown = Column(String(40), index=True)
    HistoryOfIncorporation = Column(String(500))
 
    def __init__(self, TownName, County, YearEstablished, 
        ParentTown, HistoryOfIncorporation):
        self.TownName = TownName
        self.County = County
        self.YearEstablished = YearEstablished
        self.ParentTown = ParentTown
        self.HistoryOfIncorporation = HistoryOfIncorporation
 
 
    def __repr__(self):
        return (
            f"<ConnecticutCity {self.TownName}, {self.County}, " \
            f"{self.YearEstablished}, {self.ParentTown}, " \
            f"{self.HistoryOfIncorporation}>"
        )
 
 
def main():
    Base.metadata.create_all(engine)
 
 
if __name__ == "__main__":
    main()
Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
  Find a string from a column of one table in another table visedwings049 8 1,180 Sep-07-2023, 03:22 PM
Last Post: deanhystad
Question Using SQLAlchemy, prevent SQLite3 table update by multiple program instances Calab 3 758 Aug-09-2023, 05:51 PM
Last Post: Calab
  SQLALCHEMY - Not selecting data from table jamesaarr 4 2,242 Nov-02-2021, 03:02 PM
Last Post: Larz60+
  pandas pivot table: How to find count for each group in Index and Column JaneTan 0 3,320 Oct-23-2021, 04:35 AM
Last Post: JaneTan
  How to create db table with SQLite and SQLAlchemy?? marcello86 1 2,322 Sep-02-2020, 03:05 PM
Last Post: marcello86

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020