问题
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