tortoise / tortoise-orm

Familiar asyncio ORM for python, built with relations in mind
https://tortoise.github.io
Apache License 2.0
4.38k stars 356 forks source link

auto_now not working #1574

Closed lichen404 closed 2 months ago

lichen404 commented 3 months ago

Describe the bug I use auto_now in my model,but when I use update method ,its updated time doesn't update

update mtheod

image

model

image image

Expected behavior auto_now works when I update data

daudln commented 3 months ago

auto_now fields are not updated on calling .update() method.

auto_now fields are updated only if .save() method is called on model instance.

Be aware that update() does an update at the SQL level and, thus, does not call any save() methods on your models, nor does it emit the pre_save or post_save signals (which are a consequence of calling Model.save()

Based on your scenario, you need to get item, set attribute you want to update and save the instance

@app.put("/movies/{pk}")
async def update_movie(pk: int, movie_in: MovieIn):
    movie = await Movie.filter(id=pk).first()
    if movie:
        # Your staffs
        await movie.save()
        return  # Your staffs
    return  # Your staffs
waketzheng commented 2 months ago

A few months ago, both auto_now and auto_now_add not work at my code. But after I change database from sqlite3 to MySQL, they work fine.