Search code examples
pythonflaskflask-sqlalchemyattributeerror

AttributeError: type object 'Post' has no attribute 'query'


I followed Corey Schafer's flask tutorial to build a social media website. However, when I got to the Create a post stage, I encountered "AttributeError: type object 'Post' has no attribute 'query'" but I don't understand why and Corey didn't encounter this problem in the video... I am really new to this and I have no idea what had gone wrong, any advice would be greatly appreciated.


Solution

  • This is because you are not using the Post(db.Model) in your model.py that does have the query method but your program is using the Post(FlaskForm) from form.py. As they have the same name your imports are overriding each other:

    # simplified
    from sm.model import Post
    from sm.forms import Post
    

    Try explicitly naming them PostModel and PostForm for easier clarification between the two.

    (You will notice that this is exactly what is done in Corey Schafers code snippets )