Answer the question
In order to leave comments, you need to log in
Error when using Sqlalchemy + Heroku Postgresql DB?
The code:
from sqlalchemy import Integer,String, DateTime ,Column, ForeignKeyConstraint, UniqueConstraint, ForeignKey
from sqlalchemy.orm import sessionmaker
from sqlalchemy.orm import relationship
from sqlalchemy.orm import scoped_session
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy import create_engine
#from sqlalchemy.pool import SingletonThreadPool
from datetime import datetime
import os
Base = declarative_base()
class User(Base):
__tablename__ = 'users'
id = Column(Integer,primary_key=True)
tg_id = Column(String)
budget = Column(Integer,default=0)
purchases = relationship("Expense",backref="user",lazy='dynamic')
def add_to_balance(income):
self.budget += int(income)
def del_from_budget(expense):
self.budget -= int(expense)
def __init__(self, tg_id):
self.tg_id = tg_id
def __repr__(self):
return '< User: {} >'.format(self.tg_id)
class Expense(Base):
""" """
__tablename__ = 'expenses'
id = Column(Integer,primary_key=True)
name = Column(String)
price = Column(Integer)
purchase_type = Column(String)
date = Column(DateTime, default=datetime.now)
customer_id = Column(String, ForeignKey('users.tg_id'))
def __init__(self,name,price,purchase_type):
self.name = name
self.price = price
self.purchase_type = purchase_type
def __repr__(self):
return '< Expense: {}, {}, {} >'.format(self.name,self.price,self.customer_id)
engine = create_engine('postgres://{данные}',echo=True)
Base.metadata.create_all(engine)
CREATE TABLE users (
id SERIAL NOT NULL,
tg_id VARCHAR,
budget INTEGER,
PRIMARY KEY (id)
)
CREATE TABLE expenses (
id SERIAL NOT NULL,
name VARCHAR,
price INTEGER,
purchase_type VARCHAR,
date TIMESTAMP WITHOUT TIME ZONE,
customer_id VARCHAR,
PRIMARY KEY (id),
FOREIGN KEY(customer_id) REFERENCES users (tg_id)
)
2020-02-06 20:49:19,930 INFO sqlalchemy.engine.base.Engine {}
2020-02-06 20:49:20,163 INFO sqlalchemy.engine.base.Engine ROLLBACK
Traceback (most recent call last):
File "C:\Users\User\Desktop\Python\TBot_Socks\venv\lib\site-packages\sqlalchemy\engine\base.py", line 1246, in _execute_context
cursor, statement, parameters, context
File "C:\Users\User\Desktop\Python\TBot_Socks\venv\lib\site-packages\sqlalchemy\engine\default.py", line 581, in do_execute
cursor.execute(statement, parameters)
psycopg2.errors.InvalidForeignKey: there is no unique constraint matching given keys for referenced table "users"
Answer the question
In order to leave comments, you need to log in
A wall of unnecessary code and text where only a translator is enough.
there is no unique constraint matching given keys for referenced table "users"
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question