简体   繁体   中英

Is it an anti-pattern to send a request object to a model method in Django?

I am currently trying to use the fat model, thin view pattern, moving almost all the logic to model methods.

While doing it, I am constantly finding myself sending a request object from a view to a model method:

model_method(request)

and using it in the following way:

def model_method(self, request):
    user_id = request.user.id
    user_type = request.user.__class__.__name__

    ...

Is this a good idea? or should I send what I want from the request object to the method, instead of the whole object, like this:

user_id = request.user.id
user_type = request.user.__class__.__name__

model_method(user_id, user_type)

What is the correct way?

@knbk's answer that he posted as a comment:

Once you start passing the request just to access one or two attributes, you're treating it a bit like a God object. You're introducing unnecessary tight coupling between the request object and your method, when you only need a User instance. Later on you might need to call this method with a user object, when you don't actually have a request object. In other cases you may need the request (eg to access the session or set a cookie), so passing the request is the only solution that makes sense

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM