简体   繁体   中英

Why SQLAlchemy could not assemble any primary key columns for mapped table?

I am trying to make a flask web application that takes input from the user and saves it into the database (sqlite3). I have defined a class Flight for 'flights' table to register the flights through which customer will travel. And a different 'passengers' table to store the passenger's name.

====================================================================

I am running code in Visual Studio 2019 on Windows 7 OS.

  • Python 3.7 64-bit
  • Flask-SQLAlchemy 2.4.0
  • SQLAlchemy 1.3.4
  • Flask 0.12.4
  • pip 19.1.1

====================================================================

This is my model class.

import os
from flask import Flask
from flask_sqlalchemy import SQLAlchemy

db=SQLAlchemy()

class Flight(db.Model):
    """Flight class"""
    __tablename__ = "flights"
    id = db.Column(db.Integer, pimary_key=True)
    origin = db.Column(db.String, nullable=False)
    destination = db.Column(db.String, nullable=False)
    duration = db.Column(db.Integer, nullable=False)

class Passenger(db.Model):
    """Passenger class"""
    __tablename__ = "passengers"
    id = db.Column(db.Integer, pimary_key=True)
    name = db.Column(db.String, nullable=False)
    flight_id = db.Column(db.String, db.Foreignkey("flights.id"), nullable=False)

This is my Flask code:

import csv
import os
from datetime import datetime
from flask import Flask, render_template, request
from models import *

app = Flask(__name__)
@app.route('/')
def index():
    flights = Flight.query.all()
    return render_template("index.html", flights=flights)

@app.route('/book', methods=["POST"])
def book():
    """Book a flight"""
    #Get form information
    name=request.form.get("name")
    try:
        flight_id=int(request.form.get("flight_id"))
    except Value_Error:
        return render_template('error.html', message='Invalid flight number')

    #Make sure flight exists:
    flight=Flight.query.get(flight_id)
    if flight is None:
        return render_template("error.html", message="No such flight with that id.")

    #Add Passenger
    passenger=Passenger(name=name, flight_id=flight_id)
    db.session.add(passenger)
    db.session.commit()
    return render_template("success.html")

@app.route("/flights")
def flights():
    """List all flights"""
    flights=Flight.query.all()
    return render_template("flights.html", flights=flights)

@app.route("/flights/<int:flight_id>")
def flight(flight_id):
    """List details about a single flight"""

    #Make sue flight exists
    flight=Flight.query.get(flight_id)
    if flight is None:
        return render_template("error.html", message="No such flights")

    #Get all passengers
    passengers=Passenger.query.filter.by(flight_id=flight_id).all()
    return render_template("flight.html", flight=flight, passengers=passengers)

if __name__=="__main__":
    app.run(debug=True, port=5000)

This is the error that I am getting:

C:\Program Files (x86)\Microsoft Visual Studio\Shared\Python37_64\lib\site-packages\sqlalchemy\sql\base.py:299: SAWarning: Can't validate argument 'pimary_key'; can't locate any SQLAlchemy dialect named 'pimary'
  % (k, dialect_name)
Traceback (most recent call last):
  File "c:\program files (x86)\microsoft visual studio\2019\community\common7\ide\extensions\microsoft\python\core\ptvsd_launcher.py", line 119, in <module>
    vspd.debug(filename, port_num, debug_id, debug_options, run_as)
  File "c:\program files (x86)\microsoft visual studio\2019\community\common7\ide\extensions\microsoft\python\core\Packages\ptvsd\debugger.py", line 41, in debug
    run(address, filename, *args, **kwargs)
  File "c:\program files (x86)\microsoft visual studio\2019\community\common7\ide\extensions\microsoft\python\core\Packages\ptvsd\_local.py", line 80, in run_file
    run(argv, addr, **kwargs)
  File "c:\program files (x86)\microsoft visual studio\2019\community\common7\ide\extensions\microsoft\python\core\Packages\ptvsd\_local.py", line 140, in _run
    _pydevd.main()
  File "c:\program files (x86)\microsoft visual studio\2019\community\common7\ide\extensions\microsoft\python\core\Packages\ptvsd\_vendored\pydevd\pydevd.py", line 2329, in main
    globals = debugger.run(setup['file'], None, None, is_module)
  File "c:\program files (x86)\microsoft visual studio\2019\community\common7\ide\extensions\microsoft\python\core\Packages\ptvsd\_vendored\pydevd\pydevd.py", line 1664, in run
    return self._exec(is_module, entry_point_fn, module_name, file, globals, locals)
  File "c:\program files (x86)\microsoft visual studio\2019\community\common7\ide\extensions\microsoft\python\core\Packages\ptvsd\_vendored\pydevd\pydevd.py", line 1671, in _exec
    pydev_imports.execfile(file, globals, locals)  # execute the script
  File "c:\program files (x86)\microsoft visual studio\2019\community\common7\ide\extensions\microsoft\python\core\Packages\ptvsd\_vendored\pydevd\_pydev_imps\_pydev_execfile.py", line 25, in execfile
    exec(compile(contents+"\n", file, 'exec'), glob, loc)
  File "C:\Users\Master 1TB\source\repos\final_python_dbflask\final_python_dbflask\final_python_dbflask.py", line 10, in <module>
    from models import *
  File "C:\Users\Master 1TB\source\repos\final_python_dbflask\final_python_dbflask\models.py", line 16, in <module>
    class Flight(db.Model):
  File "C:\Program Files (x86)\Microsoft Visual Studio\Shared\Python37_64\lib\site-packages\flask_sqlalchemy\model.py", line 67, in __init__
    super(NameMetaMixin, cls).__init__(name, bases, d)
  File "C:\Program Files (x86)\Microsoft Visual Studio\Shared\Python37_64\lib\site-packages\flask_sqlalchemy\model.py", line 121, in __init__
    super(BindMetaMixin, cls).__init__(name, bases, d)
  File "C:\Program Files (x86)\Microsoft Visual Studio\Shared\Python37_64\lib\site-packages\sqlalchemy\ext\declarative\api.py", line 75, in __init__
    _as_declarative(cls, classname, cls.__dict__)
  File "C:\Program Files (x86)\Microsoft Visual Studio\Shared\Python37_64\lib\site-packages\sqlalchemy\ext\declarative\base.py", line 131, in _as_declarative
    _MapperConfig.setup_mapping(cls, classname, dict_)
  File "C:\Program Files (x86)\Microsoft Visual Studio\Shared\Python37_64\lib\site-packages\sqlalchemy\ext\declarative\base.py", line 160, in setup_mapping
    cfg_cls(cls_, classname, dict_)
  File "C:\Program Files (x86)\Microsoft Visual Studio\Shared\Python37_64\lib\site-packages\sqlalchemy\ext\declarative\base.py", line 194, in __init__
    self._early_mapping()
  File "C:\Program Files (x86)\Microsoft Visual Studio\Shared\Python37_64\lib\site-packages\sqlalchemy\ext\declarative\base.py", line 199, in _early_mapping
    self.map()
  File "C:\Program Files (x86)\Microsoft Visual Studio\Shared\Python37_64\lib\site-packages\sqlalchemy\ext\declarative\base.py", line 696, in map
    self.cls, self.local_table, **self.mapper_args
  File "<string>", line 2, in mapper
  File "<string>", line 2, in __init__
  File "C:\Program Files (x86)\Microsoft Visual Studio\Shared\Python37_64\lib\site-packages\sqlalchemy\util\deprecations.py", line 130, in warned
    return fn(*args, **kwargs)
  File "C:\Program Files (x86)\Microsoft Visual Studio\Shared\Python37_64\lib\site-packages\sqlalchemy\orm\mapper.py", line 716, in __init__
    self._configure_pks()
  File "C:\Program Files (x86)\Microsoft Visual Studio\Shared\Python37_64\lib\site-packages\sqlalchemy\orm\mapper.py", line 1397, in _configure_pks
    % (self, self.persist_selectable.description)
sqlalchemy.exc.ArgumentError: Mapper mapped class Flight->flights could not assemble any primary key columns for mapped table 'flights'
The thread 0x1 has exited with code 0 (0x0).
The program 'python.exe' has exited with code 0 (0x0).

I don't have two primary_key's defined in the same table, still I am getting this error Mapper mapped class Flight->flights could not assemble any primary key columns for mapped table 'flights' . I am a student trying to learn database using SQLAlchemy. Please help me with this.

In both your Flight and Passenger class, you misspelled primary_key :

id = db.Column(db.Integer, pimary_key=True)
                          # ^ Note lack of 'r' here

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM