如何在 Django 的 url 正则表达式中使用查询结果

How to use query results in url regex in Django

我想使用数据库查询来生成我的 URL 配置。类似于:

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

然后是像这样的正则表达式:

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

我的想法是 URL 像:

/state/ca/
/state/az/

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

有什么好的方法吗?我尝试了明显的变化,即:

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

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

想法?

为什么需要在 URL 模式本身中对此进行约束?最好接受所有双字母代码,然后查看视图。

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

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