I'm wondering why the slug field does not get updated when calling the PUT api (provided I haven't done anything wrong). It seems like the root_validator is not inherited by the UpdateBlog Pydantic model. Can you please shed light on this?
It happened because the root validator was designed to slugify the title and ignore the actual slug that we are sending.
We did not take into consideration if we are sending a slug value. To take it into consideration we need to modify values["slug"] = values.get("title").replace(" ","-").lower()
@root_validator(pre=True) def generate_slug(cls, values): if 'title' in values: values["slug"] = values.get("slug") or values.get("title").replace(" ","-").lower() return values
By doing this change, we are giving first preference to the slug value being sent. If the slug value is not there, we will slugify the title and use it.
Hi Sourabh, I think I got the reason why this is happening.
The responsibility is not on the UpdateBlog Pydantic model, which is indeed correctly inheriting the
@root_validator, but rather in the implementation of the
update_blog_by_id function defined in the repository folder.
def update_blog_by_id(id: int, blog: UpdateBlog, db: Session, author_id: int = 1): blog_in_db = db.query(Blog).filter(Blog.id == id).first() if not blog_in_db: ... if not blog_in_db.author_id == author_id: ... blog_in_db.title = blog.title blog_in_db.content = blog.content db.add(blog_in_db) db.commit() return blog_in_db
As such, the slug field does not get any update in the db. We should add
blog_in_db.slug = blog.slug to make it work.
Brige the gap between Tutorial hell and Industry. We want to bring in the culture of Clean Code, Test Driven Development.
We know, we might make it hard for you but definitely worth the efforts.
Follow us on our social media channels to stay updated.