我正在尝试一个RESTful示例。我正在使用Flask,棉花糖,sqlalchemy和Postgres DB 问题在于,一张表中的FK似乎被视为字段。
我尝试了谷歌搜索,但没有成功。
这就是我所拥有的
Model.py
class Customer(db.Model):
__tablename__ = 'customers'
__table_args__ = {"schema": "business"}
id = db.Column(db.Integer, primary_key=True)
name = db.Column(db.Text, nullable=False)
status = db.Column(db.Integer, nullable=False)
# Define the JSON schemas
class CustomerSchema(ma.ModelSchema):
class Meta:
model = Customer
class Token(db.Model):
__tablename__ = 'tokens'
__table_args__ = {"schema": "business"}
id = db.Column(db.Integer, primary_key=True)
token = db.Column(db.String(60), nullable=False)
name = db.Column(db.String(30), nullable=False)
token_type = db.Column(db.Integer, nullable=False, default=0)
description = db.Column(db.String(60), nullable=True)
created = db.Column(db.TIMESTAMP,
server_default=db.func.timezone('UTC',
db.func.current_timestamp()),
nullable=True)
expires = db.Column(db.TIMESTAMP,
server_default=db.func.timezone('UTC',
db.func.current_timestamp()),
nullable=True)
# Add FK to Customer
customer_id = db.Column(db.Integer, db.ForeignKey('business.customers.id',
ondelete='CASCADE'),
nullable=False)
customer = db.relationship('Customer',
backref=db.backref('customers', lazy='dynamic'))
# defines the JSON schemas
class TokenSchema(ma.ModelSchema):
class Meta:
model = Token
这是我的终点代码:
# Get ALL Tokens
class TokenList(Resource):
def get(self):
tokens = Token.query.all()
tokens = tokens_schema.dump(tokens)
return {'status': 'success', 'data': tokens}, 200
当我调用此终点时,出现此错误:
sqlalchemy.exc.ProgrammingError: (psycopg2.ProgrammingError) column tokens.customer_id does not exist
这是真的!该表上不存在它是FK
通过此(生成的)SQL:
SQL: 'SELECT business.tokens.id AS business_tokens_id, business.tokens.token AS business_tokens_token, business.tokens.name AS business_tokens_name, business.tokens.token_type AS business_tokens_token_type, business.tokens.description AS business_tokens_description, business.tokens.created AS business_tokens_created, business.tokens.expires AS business_tokens_expires, business.tokens.customer_id AS business_tokens_customer_id \nFROM business.tokens'
我在令牌表中的所有行之后,因此我不尝试将其连接到客户表。我不明白为什么将它包含在select语句中?
感谢所有帮助!