Django中两个模型的一个url模式 [英] One url pattern for two models in Django

查看:138
本文介绍了Django中两个模型的一个url模式的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述



我有两个模型:游戏和类别,我想要一个url模式为这两个:

  ios-games / category_name 

  ios-games / game_name 

所以类别模式应该先行,如果slug不在那里,它应该检查游戏模式。



有可能没有为这两个模型创建一个大的视图?



不幸的是, url.py 不起作用,如果在第一个模式中找不到对象,它不会进一步查找...

解决方案

我不认为有办法说你想从视图继续查看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.

这篇关于Django中两个模型的一个url模式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆