Django Order_BY自定义功能

时间:2016-01-01 19:03:37

标签: django sql-order-by models

我在模型roll_numb中有字段。 roll_numb的值如下。

070-001
070-007
070-343
080-002
080-008

当我order_by roll_numb时,排序就像上面一样。 我想将roll_numb拆分为-并按余数排序。 (即001,002,008)

代码

class Meta:
        ordering = ['roll_numb']

2 个答案:

答案 0 :(得分:5)

使用自定义字段注释您的查询集:

# Imports
import webiopi
import time
import urllib.request
import requests

# Enable debug output
webiopi.setDebug()

# Retrieve GPIO lib
GPIO = webiopi.GPIO

SWITCH = 21
SERVO  = 23
LED0   = 24
LED1   = 25

# Called by WebIOPi at script loading
def setup():
    webiopi.debug("Script with macros - Setup")
    # Setup GPIOs
    GPIO.setFunction(SWITCH, GPIO.IN)
    #GPIO.setFunction(SERVO, GPIO.PWM)
    #GPIO.setFunction(LED0, GPIO.PWM)
    #GPIO.setFunction(LED1, GPIO.OUT)

    #GPIO.pwmWrite(LED0, 0.5)        # set to 50% ratio
    #GPIO.pwmWriteAngle(SERVO, 0)    # set to 0 (neutral)
    #GPIO.digitalWrite(LED1, GPIO.HIGH)



# Looped by WebIOPi
def loop():
    # Toggle LED each 5 seconds
    #value = not GPIO.digitalRead(LED1)
    #GPIO.digitalWrite(LED1, value)
    webiopi.sleep(5)        

# Called by WebIOPi at server shutdown
def destroy():
    webiopi.debug("Script with macros - Destroy")
    # Reset GPIO functions
    #GPIO.setFunction(SWITCH, GPIO.IN)
    #GPIO.setFunction(SERVO, GPIO.IN)
    #GPIO.setFunction(LED0, GPIO.IN)
    #GPIO.setFunction(LED1, GPIO.IN)
    #gpio0 = webiopi.deviceInstance("gpio0")
    #gpio0.digitalWrite(0, 1)

# A macro which says hello
@webiopi.macro
def HelloWorld():
    urllib.request.urlopen("http://192.168.0.200:9090/?dW5pdDFPTg==").read()

# A macro without args which return nothing
@webiopi.macro
def HelloWorld2():
    urllib.request.urlopen("http://192.168.0.200:9090/?dW5pdDFPRkY=").read()

@webiopi.macro
def get_DoorStatus(arg0):
    x = urllib.request.urlopen('http://192.168.0.200:9090/')
    if 'Switch1Off' in x.read():
    print (p0)
    return "%d" % p0 # returns "0" or "1"

如果您想始终订购模型,只需将该注释移至模特的经理:

from django.db.models.functions import Substr

YourModel.objects.annotate(roll_split=Substr('roll_numb', 5)).order_by('roll_split')

答案 1 :(得分:3)

我认为不可能在Django的ORM范围内通过queryset方法订购model

因此,为了按您的自定义方法对queryset进行排序,我推荐两种方法:

<强>第一

qs = mymodel.objects.all()
qs = sorted(qs, key: lambda i: i.roll_numb().split('-')[1])

<强>第二

在模型中添加另一个字段,因此请启用Django的ORM按所需值排序:

MyModel(models.Model):
    class Meta:
        ordering = ['roll_numb_splitted']

   roll_numb_splitted = models.Charfield(max_length=3)

   def save(self, *args, **kwargs):
        # this is a check to run once
        if not self.pk:
            self.roll_numb_splitted = self.roll_numb().split('-')[1]
        return super(MyModel, self).save(*args, **kwargs)