[Answer]-Sorting by a GenericIPAddressField in Django admin site

1👍

One solution you could look at using is converting the IP address to int, storing both in the database.

Basically you take the IP address and split it on each ..

This will give you something like:

Octet 1: 192
Octet 2: 168
Octet 3: 1
Octet 4: 10

You then use the following maths to give you an integer which can be ordered.

(Octet1 * 256^3) + (Octet2 * 256^2) + (Octet3 * 256) + (Octet4)
3221225472 + 11010048 + 256 + 10 = 3232235786

More information can be found here: http://www.aboutmyip.com/AboutMyXApp/IP2Integer.jsp

0👍

This isn’t the answer you wanted to hear, but your database probably doesn’t support an IP address field type, so Django uses a text field type with text sorting semantics.

PostgreSQL has native support for IP addresses (both IPv4 and IPv6), including natural sorting.

👤intgr

0👍

Based on intgr’s comment about IPv6, I just wanted to include the code I ended up using, which is based on Matt’s approach of storing an integer version of the IP but plays nicely with IPv6.

import socket, struct
def ip_to_int(ip):
    ip = unicode(ip)
    try:
        return struct.unpack('!I', socket.inet_pton(socket.AF_INET, ip))[0]
    except socket.error:
        try:
            hi, lo = struct.unpack('!QQ', socket.inet_pton(socket.AF_INET6, ip))
            return (hi << 64) | lo
        except socket.error:
            return 0

Unfortunately I can’t remember now if I wrote this myself or if I found it online somewhere, so I can’t give credit if credit is due.

Leave a comment