Django重击网址 - 如何处理碰撞?

时间:2021-11-12 00:19:18

I'm currently working on a toy project in Django.

我目前正在Django做一个玩具项目。

Part of my app allows users to leave reviews. I'd like to take the title of the review and slugify it to create a url.

我的应用程序的一部分允许用户留下评论。我想获取评论的标题并将其强化以创建一个网址。

So, if a user writes a review called "The best thing ever!", the url would be something like: www.example.com/reviews/the-best-thing-ever.

因此,如果用户撰写了一篇名为“有史以来最棒的东西!”的评论,那么该网址就像是:www.example.com/reviews/the-best-thing-ever。

That's all well and good, but what is the best way to handle case where two users pick the same title? I don't want to make the title required to be unique.

这一切都很好,但是处理两个用户选择相同标题的情况的最佳方法是什么?我不想让标题必须是唯一的。

I've thought about adding the review id in the url somewhere, but I'd like to avoid that extra info for any urls that don't collide.

我曾想过在某个地方的网址中添加评论ID,但我想避免任何不碰撞的网址的额外信息。

Any ideas?

有任何想法吗?

4 个解决方案

#1


6  

One thing I never liked about the unique slug fields/methods is that if you have a lot of *es for a single title, you'll end up running several queries to try and determine an available slug. I know you mentioned you don't want to show the id for non-*ing slugs, but, as far as performance, I think it's the better route to take. To make the URL a little nicer looking, I prefer also to embed the id before the slug, so that a URL takes the form of www.example.com/reviews/1/the-best-thing-ever.

关于独特的slug字段/方法我不喜欢的一件事是,如果你对单个标题有很多冲突,你最终会运行几个查询来尝试确定一个可用的slug。我知道你提到你不想显示非冲突slu的id,但是,就性能而言,我认为这是更好的选择。为了使URL更好看,我更喜欢在slug之前嵌入id,以便URL采用www.example.com/reviews/1/the-best-thing-ever的形式。

#2


6  

I would recommend something like AutoSlugField. It has a few options available with respect to configuring uniqueness (unique and unique_with), and has the added benefit of being able to automatically generate slugs based on another field on your model, if you so choose.

我会推荐像AutoSlugField这样的东西。它有一些关于配置唯一性(unique和unique_with)的选项,并且还有一个额外的好处,即如果您愿意,可以根据模型上的另一个字段自动生成slug。

#3


2  

from django.template.defaultfilters import slugify

def slugify_unique(value, model, slugfield="slug"):
        suffix = 0
        potential = base = slugify(value)
        while True:
            if suffix:
                potential = "-".join([base, str(suffix)])
            if not model.objects.filter(**{slugfield: potential}).count():
                return potential
            suffix += 1      
"""
above function is not my code, but i don't remember exactly where it comes from
you can find many snippets with such solutions searching for 'unique slug' and so
"""


class ReviewForm(forms.ModelForm):

    def save(self, user, commit=True):    
        self.instance.slug = slugify_unique(self.cleaned_data['title'], self.Meta.model)                       
        review = super(ReviewForm, self).save(commit)
        review.save()
        return review

    class Meta:
        model = Review

of course change the appropriate names and form definition, but you get the idea :)

当然改变了相应的名称和表单定义,但你明白了:)

#4


0  

I would (in the form validation) just check to see if the slug is used, and then add something to it, either a number "my-cool-idea_2" or the actual id

我会(在表单验证中)只是检查是否使用了slug,然后添加一些东西,或者是一个数字“my-cool-idea_2”或者实际的id

#1


6  

One thing I never liked about the unique slug fields/methods is that if you have a lot of *es for a single title, you'll end up running several queries to try and determine an available slug. I know you mentioned you don't want to show the id for non-*ing slugs, but, as far as performance, I think it's the better route to take. To make the URL a little nicer looking, I prefer also to embed the id before the slug, so that a URL takes the form of www.example.com/reviews/1/the-best-thing-ever.

关于独特的slug字段/方法我不喜欢的一件事是,如果你对单个标题有很多冲突,你最终会运行几个查询来尝试确定一个可用的slug。我知道你提到你不想显示非冲突slu的id,但是,就性能而言,我认为这是更好的选择。为了使URL更好看,我更喜欢在slug之前嵌入id,以便URL采用www.example.com/reviews/1/the-best-thing-ever的形式。

#2


6  

I would recommend something like AutoSlugField. It has a few options available with respect to configuring uniqueness (unique and unique_with), and has the added benefit of being able to automatically generate slugs based on another field on your model, if you so choose.

我会推荐像AutoSlugField这样的东西。它有一些关于配置唯一性(unique和unique_with)的选项,并且还有一个额外的好处,即如果您愿意,可以根据模型上的另一个字段自动生成slug。

#3


2  

from django.template.defaultfilters import slugify

def slugify_unique(value, model, slugfield="slug"):
        suffix = 0
        potential = base = slugify(value)
        while True:
            if suffix:
                potential = "-".join([base, str(suffix)])
            if not model.objects.filter(**{slugfield: potential}).count():
                return potential
            suffix += 1      
"""
above function is not my code, but i don't remember exactly where it comes from
you can find many snippets with such solutions searching for 'unique slug' and so
"""


class ReviewForm(forms.ModelForm):

    def save(self, user, commit=True):    
        self.instance.slug = slugify_unique(self.cleaned_data['title'], self.Meta.model)                       
        review = super(ReviewForm, self).save(commit)
        review.save()
        return review

    class Meta:
        model = Review

of course change the appropriate names and form definition, but you get the idea :)

当然改变了相应的名称和表单定义,但你明白了:)

#4


0  

I would (in the form validation) just check to see if the slug is used, and then add something to it, either a number "my-cool-idea_2" or the actual id

我会(在表单验证中)只是检查是否使用了slug,然后添加一些东西,或者是一个数字“my-cool-idea_2”或者实际的id