Sort django models by specific criteria

I want to sort django models by specific criteria

models.py


class Tag(models.Model):
    #ID given to the tag
    tag_id = models.AutoField(primary_key=True, verbose_name='Tag ID')
    #Tag name
    tag_name = models.CharField(max_length=20, verbose_name='Tag name')

    def __str__(self):
        return str(self.tag_name)

class IdeaTagMap(models.Model):
    ideatag_id = models.AutoField(primary_key=True, verbose_name='Idea tag ID')
    #Posted to be linked
    idea = models.ForeignKey(PostIdea, on_delete=models.CASCADE)
    #Tags to be tied
    tag = models.ForeignKey(Tag, on_delete=models.CASCADE)

    def __str__(self):
        return str(self.idea) + '_' + str(self.tag)

When there is such a model, the Tag model is basically displayed in the order of addition, but I want to be able to display the display order in the order of the number of times referenced in IdeaTagMap.

The fastest way is to use models.Manager.

models.py


#Added as Tag Manager
class TagManager(models.Manager):
    #Show how many times each tag is used in IdeaTagMap and sort in descending order.
    def get_queryset(self):
        return super().get_queryset().annotate(
            ideatagmap_count= models.Count('ideatagmap')
        ).order_by('-ideatagmap_count')

class Tag(models.Model):
    tag_id = models.AutoField(primary_key=True, verbose_name='Tag ID')
    tag_name = models.CharField(max_length=20, verbose_name='Tag name')
    #add to
    objects = TagManager()

    def __str__(self):
        return str(self.tag_name) + '(' + str(self.ideatagmap_count) + ')'

class IdeaTagMap(models.Model):
    ideatag_id = models.AutoField(primary_key=True, verbose_name='Idea tag ID')
    #Posted to be linked
    idea = models.ForeignKey(PostIdea, on_delete=models.CASCADE)
    #Tags to be tied
    tag = models.ForeignKey(Tag, on_delete=models.CASCADE)

    def __str__(self):
        return str(self.idea) + '_' + str(self.tag)

You can sort the order by creating this TagManager.

reference image スクリーンショット (13).png

Consideration, impression

It is thought that the trend function etc. also sets the time axis to these, so I would like to study more and implement it.

Recommended Posts

Sort django models by specific criteria
Models in Django
Sort by pandas
Sort by dict type value value
Data acquired by Django releted
Create and list Django models
Sort by file modification date
Sort by date in python