Django DRY URLs for Model access
Reader's Digest version: How do I get data (either single row if specified or full table) from a model by taking a URL argument of the model's name without hardcoding the URLconfs to match each model? For more details, read on:
I'm making an app that has three models, and I want to make a simple view that takes a name of a model,开发者_StackOverflow社区 and spit out the model's default manager's Model.manager.all(),
and if there's a slug, a single object matching that slug. I don't know how to do this, so I'm running into problems with having to make views/URLconfs for EACH model individually.
Here's what the URLconfs are looking like:
(r'^model1/$', 'model1_index_view', 'model1_index'),
(r'^model1/(?P<slug>[-\w]+)/$', 'model1_detail_view', 'model1_detail'),
(r'^model2/$', 'model2_index_view', 'model2_index'),
It goes on a little bit longer, but I think you get the picture. I'm ending up hardcoding a relatively large amount of URLconfs to do something that I'm thinking I can do with perhaps one View that takes a Model name as an argument and optionally a slug. My concern is, what happens if someone specifies a Model name of say... User? Is there a snippet of code to get a list of models from an app and make sure it matches one of 'em and not a model from contrib.auth or another app?
Use get_model:
from django.db.models import get_model
def my_view(request, model_name, item_slug):
try:
model = get_model('app_name', model_name)
except:
## throw an error
pass
objects = model.objects.get(slug=item_slug)
Then in urls:
(r'^(?P<model_name>[-\w]+/(?P<slug>[-\w]+)/$', 'model_detail_view', 'model_detail'),
精彩评论