如何在django模型中排序一个选择文件



我有一个选择文件,我需要根据CHOICES元组和这个模型中的顺序对它进行排序。py:

class MeetingMember(models.Model):
CHOICES = (
("H", "Host"),
("A", "Accepted"),
("R", "Rejected"),
("I", "Invited" )
)

status = models.CharField(max_length=9, choices=CHOICES, default="I")

我已经尝试了meta排序:

class Meta:
ordering = ('status',)

但它不工作,我需要在Host,Accepted,Rejected,Invited

中排序

您可以尝试利用Replace函数(https://docs.djangoproject.com/en/3.2/ref/models/database-functions/#replace)。该策略是用一个值来注释一个新字段,该值的字母顺序与您希望在原始字段中的自定义顺序相匹配:

from django.db.models import F, Value
from django.db.models.functions import Replace
# This generates a dictionary like {'0': 'H', '1': 'A', ...}
mapped_choices = {str(n): CHOICES[n][0] for n in range(len(CHOICES))}
# For each mapped choice we create a replacer
replacers = [
Replace('status_for_ordering', Value(original), Value(replacement)) 
for replacement, original in mapped_choices.items()
]
qs = MeetingMember.objects.all().annotate(status_for_ordering=F('status'))
for replacer in replacers:
qs = qs.annotate(status_for_ordering=replacer)
# Of course here you can still filter or do other operations before ordering
qs = qs.order_by('status_for_ordering')

此解决方案应该适用于您的示例,但当然需要进行一些调整,以防替换开始相互冲突(例如,如果您的原始状态值之一包含数字)。

相关内容

  • 没有找到相关文章