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

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

问题描述

是否可以在 Django 中为两个模型使用一个 url 模式?

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

我有两个模型:Game 和 Category,我想要这两个模型的 url 模式:

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

ios-games/category_name

ios-games/game_name

所以类别模式应该先去,如果没有slug,它应该检查游戏模式.

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?

不幸的是,url.py 中的路径顺序不起作用,如果它在第一个模式中找不到对象,它就不会继续寻找......

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

推荐答案

我认为没有办法说您想继续从视图中浏览 url.但是,您可以创建一个调用正确视图的视图.我以前做过这样的事情.类似的东西:

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天全站免登陆