0

I have a django model and a field representing an ip-address. I want order queryset of this model by ip-address value such "10.10.10.1"

I do Model.objects.order_by("ip_address"), but I get this

QuerySet["10.10.10.1", "10.10.10.11", "10.10.10.12", ...]

I want this QuerySet["10.10.10.1", "10.10.10.2", "10.10.10.3", ...]

I don't know how to do this.

Anyone have any ideas?

Mykyta
  • 160
  • 10
  • 1
    Postgresql has [data types](https://www.postgresql.org/docs/current/datatype-net-types.html) to represent network addresses. Using the `inet` to for your column would yield the ordering you want (plus some useful [functions and operators](https://www.postgresql.org/docs/current/functions-net.html)). If changing the column's type is possible that would be my first recommandation. – Marth Apr 21 '20 at 12:18
  • See this post about custom order by in django - https://stackoverflow.com/questions/7619554/django-custom-order-by – Tom Ron Apr 21 '20 at 12:22
  • @Marth i found field `GenericIPAddressField` in django models. I think it will be helpful for me. Thanks. – Mykyta Apr 21 '20 at 12:26
  • @TomRon it is useful to me. thanks. – Mykyta Apr 21 '20 at 12:29

1 Answers1

0

How I did it:

class IPAddressManager(models.Manager):

    def get_queryset(self):
        return super().get_queryset().extra(
            select={'ordered_ip_addresses': "string_to_array(ip_address, '.')::int[]", },
        )

    def all_ordered_objects(self):
        return self.order_by("ordered_ip_addresses")


class IPAddress(models.Model):

    objects = IPAddressManager()
    ip_address = models.CharField()


now when we will call IPAddress.objects.all_ordered_objects() we will have really ordered set

Mykyta
  • 160
  • 10