One url pattern for two models in Django

前端 未结 1 1287
执念已碎
执念已碎 2021-01-25 04:03

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-g         


        
1条回答
  •  离开以前
    2021-01-25 04:45

    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.

    0 讨论(0)
提交回复
热议问题