请求在django models.py [英] request in django models.py
本文介绍了请求在django models.py的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我可能是一个noob的问题,但是...有一种在models.py中使用请求的方法?
像
class MyModel(models.Model):
User = models.ForeignKey(default = request.user)
...其他字段...
或者也可以使用post_init方法进行此工作。
谢谢。
解决方案
这个具体的例子给了它在Django中没有用。 请求确实有它们的上下文(HTTP发生的上下文),因此当您实例化 MyModel
时,它可能或不可用。 p>
您可以在您的视图中执行:
def index(request):
myModel = MyModel(request.user)
在您的模型中:
class MyModel(models.Model):
user = models.ForeignKey(User)
def __init __(self,pUserName):
self.user = User.objects.get(userName = pUserName)
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.
解决方案
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)
这篇关于请求在django models.py的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文