Skip to content Skip to sidebar Skip to footer

How To Convert Python Object Into String?

QuerySelectField is displaying the query correctly but its not saving in the database, it shows the following error while submitting. ProgrammingError: (ProgrammingError) can't ada

Solution 1:

Your problem lies here:

form.populate_obj(article)

This basically assigns the form field values to the database object's corresponding fields. However, you are not using a SQLAlchemy relationship (you should!) so article.category needs to contain the name (why not ID?!) of the category. However, the QuerySelectField has the database object (i.e. a Category instance) as its value.

You have three options; the third one is the preferred one:

  • Use a normal SelectField with choices populated from the database
  • Don't use populate_obj but assign the category manually using

    article.category = form.category.data.name
    
  • Rename the category column in Article to e.g. category_name and use a relationship() so Article.category does not contain the name but a Category object.

Solution 2:

The category relationship in your Article model is not correct. It has two problems:

  1. you have not provided the data type for the column.
  2. Article.category needs to be a relationship, not a column.

If you modify your Article class to something like this things should improve:

class Article(Base):
    ...
    category_name = Column(String(100), ForeignKey(Category.name), nullable=False)
    category = relationship(Category)

If you do that SQLAlchemy will know that the category property must be a Category instance and will automatically load and save Category instances as needed.

Solution 3:

Add Relationship to your Model Fields.

Post a Comment for "How To Convert Python Object Into String?"