@RaymanPy

Ошибка при использовании Sqlalchemy + Heroku Postgresql DB?

Код:
Код

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)


ошибка:
spoiler

2020-02-06 20:49:18,809 INFO sqlalchemy.engine.base.Engine select version()
2020-02-06 20:49:18,809 INFO sqlalchemy.engine.base.Engine {}
2020-02-06 20:49:19,006 INFO sqlalchemy.engine.base.Engine select current_schema()
2020-02-06 20:49:19,007 INFO sqlalchemy.engine.base.Engine {}
2020-02-06 20:49:19,203 INFO sqlalchemy.engine.base.Engine SELECT CAST('test plain returns' AS VARCHAR(60)) AS anon_1
2020-02-06 20:49:19,203 INFO sqlalchemy.engine.base.Engine {}
2020-02-06 20:49:19,306 INFO sqlalchemy.engine.base.Engine SELECT CAST('test unicode returns' AS VARCHAR(60)) AS anon_1
2020-02-06 20:49:19,307 INFO sqlalchemy.engine.base.Engine {}
2020-02-06 20:49:19,407 INFO sqlalchemy.engine.base.Engine show standard_conforming_strings
2020-02-06 20:49:19,407 INFO sqlalchemy.engine.base.Engine {}
2020-02-06 20:49:19,621 INFO sqlalchemy.engine.base.Engine
CREATE TABLE users (
	id SERIAL NOT NULL, 
	tg_id VARCHAR, 
	budget INTEGER, 
	PRIMARY KEY (id)
)


2020-02-06 20:49:19,621 INFO sqlalchemy.engine.base.Engine {}
2020-02-06 20:49:19,829 INFO sqlalchemy.engine.base.Engine COMMIT
2020-02-06 20:49:19,929 INFO sqlalchemy.engine.base.Engine
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"
  • Вопрос задан
  • 155 просмотров
Решения вопроса 1
Melkij
@Melkij
PostgreSQL DBA
Стена ненужного кода и текста там где достаточно лишь переводчика.
there is no unique constraint matching given keys for referenced table "users"

Переведите.
Посмотрите на свои foreign key
Найдите что СУБД возмущается конечно имея полные на то основания
Ответ написан
Пригласить эксперта
Ответы на вопрос 1
@RaymanPy Автор вопроса
tg_id = Column(String,unique=True)
Ответ написан
Комментировать
Ваш ответ на вопрос

Войдите, чтобы написать ответ

Похожие вопросы