SQLalchemy AttributeError: 'str' object has no attribute '_sa_instance_state'

前端 未结 3 1028
野性不改
野性不改 2020-12-10 10:54

I\'m trying to add an item to my database with SQLAlchemy + Python, but keep getting an error.

My database_setup.py:

class company(Base):
    __table         


        
相关标签:
3条回答
  • 2020-12-10 11:26

    First of all, when defining a class in Python, it is of good practice to to start the names with an uppercase letter like this:

    class Company(Base):
        __tablename__ = 'company'
        compID = Column(Integer, primary_key = True)
        name = Column(String(80), nullable = False)
    
    class Item(Base):
        __tablename__ = 'items'
        itemID = Column(Integer, primary_key = True)
        name = Column(String(80), nullable = False)
        category = Column(String(250))
        description = Column(String(250))
        price = Column(String(8))
        compID = Column(Integer, ForeignKey('company.compID'))
        company = relationship(company)
    

    That being said, it is not why your code throws an error. :)

    The reason

    The Item constructor expects an instance of the object Company to by passed as a value of the variable company

    Solution 1: The Jawbone company does not exist in your database

    Here the answer of @alecxe is valid.

    You should replace your code with:

    JawboneUP3 = Item(itemID="1", 
                      name="Jawbone UP3", 
                      description="The latest UP!", 
                      category="tracker", 
                      price="$174.99", 
                      company=company(name="Jawbone"))
    

    Adding this object to the session and comiting the changes will actually make two entries to your database:

    • The item entry, with name "Jawbone UP3"
    • A row in the company database, a company with name "Jawbone"

    Solution 2: The Jawbone company exists in your database

    Here you should fetch the company Jawbone from your table "company" and pass it as an argument to the Item constructor, like this:

    jawbone = session.query(Company).filter_by(name="Jawbone").first()
    
    JawboneUP3 = Item(itemID="1", 
                      name="Jawbone UP3", 
                      description="The latest UP!", 
                      category="tracker", 
                      price="$174.99", 
                      company=jawbone)
    

    For the session part check this

    0 讨论(0)
  • 2020-12-10 11:33
    from flask import Flask
    from flask import request,redirect,render_template
    from flask_sqlalchemy import SQLAlchemy
    
    app=Flask(__name__)
    app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///students1.sqlite3'
    db=SQLAlchemy(app)
    
    class Categ(db.Model):
        id=db.Column(db.Integer,primary_key=True)
        name=db.Column(db.String(100))
        product=db.relationship('Product',backref='owner',lazy=True)
    
    class Product(db.Model):
        id=db.Column(db.Integer,primary_key=True)
        pname=db.Column(db.String(100))
        price=db.Column(db.Integer)
        categ_id=db.Column(db.Integer,db.ForeignKey('categ.id'))
    
    @app.route('/')
    def home():
        return 'home'
    
    @app.route('/post',methods=['POST','GET'])
    def Productform():
        ob=Categ.query.all()
        if request.method=='POST':
            owner=request.form['ca']
            user = Categ.query.filter_by(name=owner).first()
    
            user=Product(pname=request.form['pname'],price=request.form['price'],owner=user)
            db.session.add(user)
            db.session.commit()
    
            return 'submit'
    
        return render_template('product.html',ob=ob)
    
    
    
    @app.route('/categ',methods=['POST','GET'])
    def Categoryform():
        if request.method=='POST':
            user=Categ(name=request.form['cname'])
            db.session.add(user)
            db.session.commit()
    
            return 'submit'
    
        return render_template('categ.html')
    
    
    if __name__ == '__main__':
       app.run(debug=True)
       db.create_all()
    
    0 讨论(0)
  • 2020-12-10 11:38

    I think the problem is in how you are defining the related company schema:

    JawboneUP3 = item(itemID = "1", name = "Jawbone UP3", description = "The latest UP!", 
                      category = "tracker", price = "$174.99", company = "Jawbone")
                                                               # HERE^
    

    The item constructor expects a company instance but you are passing a string value. Fix it:

    JawboneUP3 = item(itemID="1", 
                      name="Jawbone UP3", 
                      description="The latest UP!", 
                      category="tracker", 
                      price="$174.99", 
                      company=company(name="Jawbone"))
    
    0 讨论(0)
提交回复
热议问题