向Django模型方法添加请求?

2024-05-23 17:51:21 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在跟踪模型上的用户状态。对于模型“Lesson”,我的状态为“Finished”、“Learning”、“Viewed”。在模型列表视图中,我要添加用户状态。最好的方法是什么?

一个想法是:将请求添加到models方法中就可以了。有可能吗?

编辑:我的意思是在模板代码中:{{lesson.get status},带有getstatus(self,request)。有可能吗?它还不起作用。


Tags: 方法代码用户模型视图模板编辑列表
2条回答

是的,您可以使用请求参数向模型中添加方法:

class MyModel(models.Model):
    fields....

    def update_status(self, request):
        make something with the request...

如果您的状态是一个更改的值,则必须将其分为两部分。

  1. 正在更新状态。这必须在视图函数中调用。然而,真正的工作属于模型。view函数调用model方法并进行保存。

  2. 显示状态。这只是状态的一些字符串表示。

模型

class MyStatefulModel( models.Model ):
    theState = models.CharField( max_length=64 )
    def changeState( self ):
        if theState is None:
            theState= "viewed"
        elif theState is "viewed":
            theState= "learning"
        etc.

查看函数

 def show( request, object_id ):
     object= MyStatefulModel.objects.get( id=object_id )
     object.changeState()
     object.save()
     render_to_response( ... )

模板

 <p>Your status is {{object.theState}}.</p>

相关问题 更多 >