Reputation: 264
So I have this kind of urls:
url(r'^(?P<loc>\w+)/(?P<ctg>\w+)/$', 'beta.views.queryCtgFromIndex'),
which as it can be seen, when accessing, for example, /loc/ctgx/ the queryCtgFromIndex is called and it calculates something based on ctgx table
i actually have 5 tables which can be queried, so the valid urls can be:
/loc/ctg1/, /loc/ctg2/, ..., /loc/ctg5/
in my view i am doing something like:
if ctg == ctg1: do something, ctg1.objects.all() etc...
if ctg == ctg2: do something, ctg2.objects.all() etc...
...
if ctg == ctg5: do something, ctg5.objects.all() etc...
The do something code is quite big and my question would be: Can I rewrite my code in some fashion to get rid of the five fors and have clean code? ...something like in bash would be, fictional example: $ctg.objects.all() ...
Upvotes: 0
Views: 57
Reputation: 28637
the contenttypes framework let you interact with models in a generic way, something like
my_model = contenttypes.objects.get(model='my model name')
my_model.model_class().objects.filter(...whatever you would normally do)
you'd probably want to use a whitelist to make sure only the user can't interact with e.g. your user model in this way, e.g.
if model_name not in ['list', 'of', 'allowed', 'models']:
return HttpResponseForbidden() #or 404
Upvotes: 3