Reputation: 818
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?
Upvotes: 1
Views: 97
Reputation: 180
You can implement django-taggit or read the docs then you will get an idea how tag can be implemented in django.
Happy Coding :)
Upvotes: 1
Reputation: 151
#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 %}
Upvotes: 1