na5tyk
na5tyk

Reputation: 181

The best way to sort by custom index

I think about the best way to sort by index column. I have model:

class ProductCategory(models.Model):
    name = models.CharField(_("Category name"), max_length=200)
    description = models.TextField()
    index = models.IntegerField(_("Index order"), default=0)

    def __str__(self):
        return self.name

Can I set index on model level? In this case I would like let user to set order categories in menu.

Upvotes: 1

Views: 678

Answers (1)

willeM_ Van Onsem
willeM_ Van Onsem

Reputation: 477265

Can I set index on model level?

You already have made a field index. You can also add a database index with the db_index=True parameter [Django-doc], to make it easier to order by and filter on the index:

class ProductCategory(models.Model):
    name = models.CharField(_("Category name"), max_length=200)
    description = models.TextField()
    index = models.IntegerField(_("Index order"), default=0, db_index=True)

    def __str__(self):
        return self.name

You can also specify that the model is by default ordered by the index, by specifing the ordering option [Django-doc]:

class ProductCategory(models.Model):
    name = models.CharField(_("Category name"), max_length=200)
    description = models.TextField()
    index = models.IntegerField(_("Index order"), default=0, db_index=True)

    class Meta:
        ordering = ['index']

    def __str__(self):
        return self.name

Unless you specify the ordering explicitly (for example with ProductCategory.objects.order_by('name')), it will then order by index.

Upvotes: 2

Related Questions