How To Convert Python Object Into String?
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 usingarticle.category = form.category.data.name
- Rename the
category
column inArticle
to e.g.category_name
and use arelationship()
soArticle.category
does not contain the name but aCategory
object.
Solution 2:
The category relationship in your Article model is not correct. It has two problems:
- you have not provided the data type for the column.
- 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?"