16

我在我的应用程序中使用 Flask-Migrate,具有以下模型:

列表拉/模型.py

from datetime import datetime

from listpull import db


class Job(db.Model):
    id = db.Column(db.Integer, primary_key=True)
    list_type_id = db.Column(db.Integer, db.ForeignKey('listtype.id'),
                             nullable=False)
    list_type = db.relationship('ListType',
                                backref=db.backref('jobs', lazy='dynamic'))
    record_count = db.Column(db.Integer, nullable=False)
    status = db.Column(db.Integer, nullable=False)
    sf_job_id = db.Column(db.Integer, nullable=False)
    created_at = db.Column(db.DateTime, nullable=False)
    compressed_csv = db.Column(db.LargeBinary)

    def __init__(self, list_type, created_at=None):
        self.list_type = list_type
        if created_at is None:
            created_at = datetime.utcnow()
        self.created_at = created_at

    def __repr__(self):
        return '<Job {}>'.format(self.id)


class ListType(db.Model):
    id = db.Column(db.Integer, primary_key=True)
    name = db.Column(db.String(80), unique=True, nullable=False)

    def __init__(self, name):
        self.name = name

    def __repr__(self):
        return '<ListType {}>'.format(self.name)

运行.py

#!/usr/bin/env python
# -*- coding: utf-8 -*-

from listpull import app, manager
manager.run()

listpull/__init__.py

from flask import Flask
from flask.ext.sqlalchemy import SQLAlchemy
from flask.ext.script import Manager
from flask.ext.migrate import Migrate, MigrateCommand
from mom.client import SQLClient
from smartfocus.restclient import RESTClient


app = Flask(__name__)
app.config.from_object('config')

db = SQLAlchemy(app)

migrate = Migrate(app, db)

manager = Manager(app)
manager.add_command('db', MigrateCommand)

...

import listpull.models
import listpull.views

我使用初始化数据库./run.py db init,然后运行./run.py db migrate,我收到以下错误:

sqlalchemy.exc.NoReferencedTableError: Foreign key associated with column 'job.list_type_id' could not find table 'listtype' with which to generate a foreign key to target column 'id'

我在这里做错了什么?

4

3 回答 3

33

您让 Flask-SQLAlchemy 为您的表选择名称。如果我没记错的话,对于一个名为ListType表名的类将是list_type(或类似的),而不是listtype您在外键中指定的类。

我的建议是您使用 指定您自己的表名__tablename__,这样它们在代码中是明确的,而不是为您神奇地确定。例如:

class Job(db.Model):
    __tablename__ = 'jobs'
    id = db.Column(db.Integer, primary_key=True)
    list_type_id = db.Column(db.Integer, db.ForeignKey('list_types.id'),
                             nullable=False)
    # ...

class ListType(db.Model):
    __tablename__ = 'list_types'
    id = db.Column(db.Integer, primary_key=True)
    name = db.Column(db.String(80), unique=True, nullable=False)
    # ...
于 2013-10-11T17:28:43.143 回答
0

就我而言,问题是我不小心用类名和表名调用了外键......就像:db.Column(db.Integer, db.ForeignKey('ClassListTypes.id')vsdb.Column(db.Integer, db.ForeignKey('list_types.id')

于 2021-01-14T09:41:50.547 回答
0

我也在为您处理很长时间的类似信息问题寻找解决方案......最后,我找到的解决方案是添加到每个“表类”行中__tablename__ = '<your_table_name>'

它似乎有助于烧瓶找到你的桌子

于 2019-06-15T11:07:07.000 回答