0

在我的所有模型中,我都有get_absolute_url()如下方法,但是使用 django-debug-toolbar 我发现它需要很多 SQL 查询。

我的对象是树形结构相关的,所以一个级别3的对象只能通过级别2知道它与哪个级别的对象相关。如何避免这么多SQL查询?通过其他对象关联对象是不好的做法吗?我是否必须像CharFields在我的 3 级模型中一样保存 1 级弹头和 2 级弹头?

@models.permalink
def get_absolute_url(self):
    return ('url_alias', None, {'level1': self.level2.level1.slug, 'level2': self.level2.slug, 'level3': self.slug})
4

1 回答 1

1

Are the slugs on your site permanent? If so, it is needless work to constantly calculate your URL like this. If your slugs are permanent, you could add a listener for saves on your model, and, at saving-time, populate a field with the URL to the object. Then your get_absolute_url could just show that.

If your slugs are not permanent, you could do as Matthew Daly suggested and store the URL-for-this-object in a cache bucket and check that. You'd still have to figure out how you wanted to clear that key (since it would need to change if you changed the slug for this object or any object higher up in the URL path).

于 2014-03-19T19:53:09.957 回答