request in django models.py

人走茶凉 提交于 2019-12-11 06:52:27

问题


I might be a noob question but... is there a way of using request in models.py?

Something like:

class MyModel (models.Model):
    User = models.ForeignKey(default=request.user)
    ...other fields...

Or maybe using the post_init method for doing this job.

Thanks.


回答1:


That specific example you gave it's not useful in Django. Request do have a context with them (the context where the HTTP happened) so it could or could not be available when you instantiate MyModel.

You can do in your view:

def index(request):
    myModel = MyModel(request.user)

And in your model:

class MyModel (models.Model):

    user = models.ForeignKey(User)

    def __init__(self, pUserName):
        self.user = User.objects.get(userName=pUserName)


来源:https://stackoverflow.com/questions/7366352/request-in-django-models-py

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!