【问题标题】:Custom order field with Django Rest Framework使用 Django Rest Framework 自定义订单字段
【发布时间】:2022-01-10 20:08:18
【问题描述】:

我有一个类似的模型

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']

我想按颜色代码订购查询集,但不是绿色、红色、黄色项目。我想订购 RED、YELLOW、GREEN 项目。

有可能吗?有类似 Java Comparator 的东西吗?提前致谢。

【问题讨论】:

  • 这是针对模型的默认排序还是针对任意查询集?

标签: django django-models django-rest-framework


【解决方案1】:

您可以使用 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']

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2015-09-25
    • 2014-08-19
    • 1970-01-01
    • 2015-08-03
    • 1970-01-01
    • 2023-03-12
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多