This has been driving me nuts how to efficiently sort IP address field in MySQL database. Ha! I managed to find one elegant solution. So let's assume we have this kind of table like in following example.
class TableFoo(BaseTable):
__tablename__ = "table_foo"
id = Column(Integer, primary_key=True)
ip_address = Column(String(50), nullable=False)
Now let us try to query for the last record.
result = (
session.query(UserLease)
.order_by(desc(TableFoo.ip_address))
.limit(1).first()
.ip_address
)
This is almost right albeit we please notice that we created IP address field as string so if we sort it like in this example we will get something like this
'10.65.4.2',
'10.65.4.123',
'10.65.4.12',
'10.65.4.1'
Nope, this is not correct :( MySQL has got function that will convert dotted notation IPv4 address to integer. Unfortunately SQLAlchemy does not support it out of the box. We can try other approach - we will use func wrapper to use MySQL function.
After rewriting sorting query with func in use we are going to do it like in following code.
result = (
session.query(UserLease)
.order_by(esc(func.INET_ATON(UserLease.ip_address)))
.limit(1)
.first()
.ip_address
)
Thank you for attention. Have a productive day.