问题描述
我正在开发/维护/管理从各种可穿戴研究设备收集的测试结果的数据库.每个设备都有三个主要组件,每个组件都有两个版本号(固件和硬件).我正在使用django应用程序来提供数据库的Web界面.版本号以正整数或三元组(主要,次要,内部版本)表示.整数很容易处理,我显然可以将三元组存储为字符串,但是作为字符串,它们将无法正确排序或正确比较,例如,如果我只希望测试固件版本小于14.xy的设备产生的结果
I'm developing/maintaining/curating a database of test results gathered from various wearable research devices. Each device has three main components, each of which has two version numbers (firmware and hardware). I'm using a django app to provide a web interface to the database. The version numbers represented either as straight integers, or as triplets (Major, minor, build). The integers are easy enough to handle, and I can obviously store the triplets as strings, but as strings they won't sort correctly or compare correctly, for example if I want only test results produced by devices with firmware version less than 14.x.y.
由于第二个小数点"分隔符,我无法使用浮点数.我想过可能通过将其存储为日期来进行破解,但这将次要数字限制为小于12,将内部数字限制为小于29,此外,我知道,这是一个糟糕的解决方案.我什至不应该承认这一点.
I can't use a float because of the second 'decimal point' separator. I thought of maybe going for a hack by storing it as a date, but that will limit minor numbers to less than 12 and build numbers to less than 29, and besides I know this is a terrible solution. I probably shouldn't even confess to having thought of it.
用一些PL/SQL扩展数据库以提供一个正确处理字符串的比较功能的简短操作,是否有一种简单的方法来做到这一点?如果没有,我什至可以在django中使用我的自定义SQL函数?
Short of extending the database with some PL/SQL to provide a comparison function that treats the strings correctly, is there a simple way to do this? If not, can I even use my custom SQL function with django?
推荐答案
将它们存储为零填充字符串:
Store them as a zero-padded strings:
>>> def sortable_version(version):
... return '.'.join(bit.zfill(5) for bit in version.split('.'))
...
>>> sortable_version('1.1')
'00001.00001'
>>> sortable_version('2')
'00002'
>>> sortable_version('2.1.10')
'00002.00001.00010'
>>> sortable_version('10.1')
'00010.00001'
>>> sortable_version('2') > sortable_version('1.3.4')
True
>>> sortable_version('10') > sortable_version('2')
True
>>> sortable_version('2.3.4') > sortable_version('2')
True
您总是可以显示这种零填充格式的常规版本:
And you can always show regular version from this zero-padded format:
>>> def normalize_version(padded_version):
... return '.'.join(bit.lstrip('0') for bit in padded_version.split('.'))
...
>>> normalize_version('00010')
'10'
>>> normalize_version('00002.00001.00010')
'2.1.10'
这篇关于如何将版本号字符串存储在Django数据库中,以便它们可正确比较/排序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!