One url pattern for two models in Django

99封情书 提交于 2019-12-02 09:49:50

问题


Is it possible to have one url pattern for two models in Django?

I have two models: Game and Category and I want one url pattern for both of these:

ios-games/category_name

and

ios-games/game_name

So category pattern should go first and if slug is not there, it should check game pattern.

Is it possible to do without creating one big view for both these models?

Unfortunately, order of paths in url.py doesn't work, if it can't find object in the first pattern it won't go looking further...


回答1:


I don't think there is a way to say that you want to continue looking through the urls from a view. You could, however, create a view which calls the correct view. I did something like this before. Something like:

class GameCategoryFactory(View):
    def dispatch(self, request, *args, **kwargs):
        game_or_category_slug = kwargs.pop('slug')

        if Category.objects.filter(name=game_or_category_slug).count() != 0:
            return CategoryView.as_view()(request, *args, **kwargs)
        elif Game.objects.filter(name=game_or_category_slug).count() != 0:
            return GameView.as_view()(request, *args, **kwargs)
        else:
            raise Http404

Of course, I am using class-based views. A function-based approach should be pretty straight-forward.



来源:https://stackoverflow.com/questions/19118637/one-url-pattern-for-two-models-in-django

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!