虽然您提供的代码在imo中还不够,但我会尽力提供帮助和解释。
根据我的理解(从未使用过
refresh_from_db
),您不能使用
从数据库刷新
这种方式。
在你的
database()
函数获取最后一个条目并尝试刷新其信息,但在获取后未对其进行更改,使其成为无意义的行(它不刷新查询,但结果返回实例)。
refresh_from_db()
如果在从数据库获取和使用特定实例信息之间对其进行了更改,则更新该信息。
以
docs
:
def test_update_result(self):
obj = MyModel.objects.create(val=1)
MyModel.objects.filter(pk=obj.pk).update(val=F('val') + 1)
# At this point obj.val is still 1, but the value in the database
# was updated to 2. The object's updated value needs to be reloaded
# from the database.
obj.refresh_from_db()
self.assertEqual(obj.val, 2)
它根本不像你想象的那样。
您的submit按钮应该调用相对类视图中的post方法,或者一些将这些值保存到数据库中的函数(您自己也提到过)。
在反向视图函数或类中,可以编写在中编写的查询
datebase()
-
Product.objects.latest('id')
.
此外,还可以使用添加的信息(例如:
return reverse('product', kwargs={'lastprod': Product.objects.latest('id')})
.
如果还不够清楚,请告诉我。