使用 Django Rest Framework 的自定义订单字段
Custom order field with Django Rest Framework
我有一个像这样的模型
class MyModel(models.Model):
COLOR_CODES = ['RED', 'YELLOW', 'GREEN']
name = models.CharField(db_column='name', max_length=200, blank=False, null=False, unique=True)
colorCode = EnumField(db_column='color_code', choices=COLOR_CODES, null=False, default='GREEN')
class Meta:
managed = True
db_table = 'MyModel'
ordering = ['colorCode']
我想按 colorCode 排序问题集,而不是按绿色、红色、黄色项目排序。我想订购红色、黄色、绿色的商品。
可能吗?有没有类似 Java 比较器的东西?提前致谢。
您可以使用 Python sorted
函数,但要利用 Django 查询:
from django.db.models import Value, IntegerField, When, Case
# Don' t set the default order in the model (this also improves performance), simply write this query when you need this particular order
MyModel.objects.annotate(order=Case(When(colorCode='RED', then=0), When(colorCode='YELLOW', then=1), default=Value(2), output_field=IntegerField())).order_by('order')
否则您可以更改模型:
from enum import Enum
class MyModel(models.Model):
class ColorCodes(Enum):
# In the admin interface you will see 'red' and not '0r' (so don't worry about ugly names), the second value is stored in the database and is used for order the queryset
red = ('red', '0r')
yellow = ('yellow', '1y')
green = ('green', '2g')
@classmethod
def get_value(cls, member):
return cls[member].value[0]
colorCode = CharField(db_column='color_code', null=False, default=ColorCodes.get_value('green'), max_length=2, choices=[x.value for x in ColorCodes])
class Meta:
managed = True
db_table = 'MyModel'
ordering = ['colorCode']
我有一个像这样的模型
class MyModel(models.Model):
COLOR_CODES = ['RED', 'YELLOW', 'GREEN']
name = models.CharField(db_column='name', max_length=200, blank=False, null=False, unique=True)
colorCode = EnumField(db_column='color_code', choices=COLOR_CODES, null=False, default='GREEN')
class Meta:
managed = True
db_table = 'MyModel'
ordering = ['colorCode']
我想按 colorCode 排序问题集,而不是按绿色、红色、黄色项目排序。我想订购红色、黄色、绿色的商品。
可能吗?有没有类似 Java 比较器的东西?提前致谢。
您可以使用 Python sorted
函数,但要利用 Django 查询:
from django.db.models import Value, IntegerField, When, Case
# Don' t set the default order in the model (this also improves performance), simply write this query when you need this particular order
MyModel.objects.annotate(order=Case(When(colorCode='RED', then=0), When(colorCode='YELLOW', then=1), default=Value(2), output_field=IntegerField())).order_by('order')
否则您可以更改模型:
from enum import Enum
class MyModel(models.Model):
class ColorCodes(Enum):
# In the admin interface you will see 'red' and not '0r' (so don't worry about ugly names), the second value is stored in the database and is used for order the queryset
red = ('red', '0r')
yellow = ('yellow', '1y')
green = ('green', '2g')
@classmethod
def get_value(cls, member):
return cls[member].value[0]
colorCode = CharField(db_column='color_code', null=False, default=ColorCodes.get_value('green'), max_length=2, choices=[x.value for x in ColorCodes])
class Meta:
managed = True
db_table = 'MyModel'
ordering = ['colorCode']