1

I am building a tags Django application to display a feed of tags ranked by "popularity."

Currently, my Tag model in models.py looks like this:

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

Ultimately, I would like to query tags in my index view in views.py kind of as follows:

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

How can I model the "popularity" concept in code?

Should I add a popularity field to the Tag model and basically count how many times a tag has been used, or is there a better, slicker way to achieve the same result?

fredperk
  • 737
  • 1
  • 9
  • 22
  • Please repeat [on topic](https://stackoverflow.com/help/on-topic) and [how to ask](https://stackoverflow.com/help/how-to-ask) from the [intro tour](https://stackoverflow.com/tour). This is a circular semantic problem: you say that you want to model "popularity", but you want us to define it for you? Where is your research on other interpretations of "popularity"? As given, this is opinion-based and too broad for Stack Overflow. – Prune Sep 05 '20 at 07:56

2 Answers2

1

django-taggit

You can implement django-taggit or read the docs then you will get an idea how tag can be implemented in django.

Happy Coding :)

Mehady
  • 140
  • 3
  • 8
1

#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 %}
NeerajSahani
  • 121
  • 1
  • 4