【问题标题】:How can I model the "popularity" concept in code?如何在代码中建模“流行”概念?
【发布时间】:2020-12-24 08:02:31
【问题描述】:

我正在构建一个tags Django 应用程序来显示按“受欢迎程度”排名的标签提要。

目前,我在 models.py 中的 Tag 模型如下所示:

class Tag(models.Model):
    tag = models.CharField(max_length=64, unique=True)
    slug = models.SlugField(max_length=64, unique=True)

最后,我想在 views.py 中的index 视图中查询标签,如下所示:

def index(request):
    context = {"tags": Tag.objects.order_by("popularity")}
    return render(request, "tags/index.html", context)

如何在代码中为“流行”概念建模?

我是否应该在Tag 模型中添加一个popularity 字段并基本上计算一个标签已使用了多少次,或者是否有更好、更流畅的方法来实现相同的结果?

【问题讨论】:

  • 请从intro tour 重复on topichow to ask。这是一个循环语义问题:你说你想为“流行”建模,但你想让我们为你定义它?您对“流行”的其他解释的研究在哪里?正如给定的那样,这是基于意见的,对于 Stack Overflow 来说过于宽泛。

标签: python django django-models tags popularity


【解决方案1】:

django-taggit

您可以实现 django-taggit 或阅读文档,然后您将了解如何在 django 中实现标签。

快乐编码:)

【讨论】:

    【解决方案2】:

    #models.py

    class Tag(models.Model):
        tag = models.CharField(max_length=64, unique=True)
        slug = models.SlugField(max_length=64, unique=True)
        
        @property
        def popularity(self):
             return self.foo_set.count()
    
    
    
    class Foo(models.Model):
        tag = models.ManyToManyField(Tag, blank=True)
    

    #views.py

    def index(request):
        context = {"tags": sorted(Tag.objects.all(), key=lambda x: x.popularity, reverse=True)}
        return render(request, "tags/index.html", context)
    

    #html

    {% for tag in tags %}
        {{ tag.tag }} - {{ tag.popularity }}
    {% empty %}
        No Tags
    {% endfor %}
    

    【讨论】:

      猜你喜欢
      • 2019-05-09
      • 1970-01-01
      • 2021-11-24
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-07-27
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多