One url pattern for two models in Django

2020-04-21 02:16发布

问题:

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.