@ParamConverter à la Django

Gergely Polonkai
Jun 7, 2015 :: 18:14

One thing I really miss from Django is Symfony’s @ParamConverter. It made my life so much easier while developing with Symfony. In Django, of course, there is get_object_or_404, but, for example, in one of my projects I had a view that had to resolve 6(!) objects from the URL, and writing get_object_or_404 six times is not what a programmer likes to do (yes, this view had a refactor later on). A quick Google search gave me one usable result (in French), but it was very generalized that I cannot always use. Also, it was using a middleware, which may introduce performance issues sometimes[citation needed]. So I decided to go with decorators, and at the end, I came up with this:

Now I can decorate my views, either class or function based, with @convert_params(User, (Article, 'aid'), (Paragraph, None, 'pid'), (AnotherObject, None, None, 'obj')) and all the magic happens in the background. The user_id parameter passed to my function will be popped off, and be resolved against the User model by using the id field; the result is put in the new user parameter. For Article, the aid parameter will be matched against the id field of the Article model putting the result into article, and finally, the another_object_id will be matched against the id field of the AnotherObject model, but in this case, the result is passed to the original function as obj.

comments powered by Disqus

Gergely Polonkai is a systems engineer of a telco company, and also a freelancer self- and software developer.

He is learning about different IT subjects since the late 1990s. These include web development, application building, systems engineering, IT security and many others. He also dug his nose deeply into free software, dealing with different types of Linux and its applications, while also writing and contributing to some open source projects.

On this site he is writing posts about different stuff he faces during work (oh my, yet another IT solutions blog), hoping they can help others with their job, or just to get along with their brand new netbook that shipped with Linux.

“I believe one can only achieve success if they follow their own instincts and listen to, but not bend under others’ opinions. If you change your course just because someone says so, you are following their instincts, not yours.”