且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

Django中两个模型的一个url模式

更新时间:2022-12-10 23:15:11

我不认为有办法说你想从视图继续查看urls。但是,您可以创建一个调用正确视图的视图。我以前做过这样的事情。类似于:

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

如果Category.objects.filter(name = game_or_category_slug).count()!= 0:
返回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

当然,我正在使用基于类的视图。基于函数的方法应该很简单。


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

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.