如何在Django中的url regex中使用查询结果

时间:2022-07-03 17:24:50

I want to use a database query to generate my URL configuration. Something like:

我想使用数据库查询来生成我的URL配置。就像是:

states = State.objects.all().values_list('pk', flat=True)

And then a regex like:

然后像正则表达式:

(r'^state/(?P<state>' + '|'.join(states) + ')/$'

The idea is that I can have URLs like:

我的想法是,我可以拥有以下网址:

/state/ca/
/state/az/

Etc.

The problem is that when I do syncdb, the query above fails, throwing a DatabaseError.

问题是,当我执行syncdb时,上面的查询失败,抛出DatabaseError。

Is there a good way to do this? I've tried the obvious change, which would be:

有没有办法做到这一点?我尝试过明显的改变,那就是:

try:
    states = State.objects.all().values_list('pk', flat=True)
except DatabaseError:
    # First sync, use dummy data
    states = []

But this doesn't work because the exception is thrown at the regex, not at the query definition.

但是这不起作用,因为在正则表达式中抛出异常,而不是在查询定义中抛出异常。

Ideas?

1 个解决方案

#1


Why do you need to constrain this in the URL pattern itself? Much better to accept all two-letter codes, and check in the view.

为什么需要在URL模式本身中约束它?接受所有双字母代码要好得多,并在视图中查看。

(r'^state/(?P<state_code>\w{2})/$'

def view_state(request, state_code):
    state = get_object_or_404(State, pk=state_code)

#1


Why do you need to constrain this in the URL pattern itself? Much better to accept all two-letter codes, and check in the view.

为什么需要在URL模式本身中约束它?接受所有双字母代码要好得多,并在视图中查看。

(r'^state/(?P<state_code>\w{2})/$'

def view_state(request, state_code):
    state = get_object_or_404(State, pk=state_code)