在Django模型上定义排序键 [英] Define sorting key on Django model
问题描述
我有两个Django模型,其中一个引用另一个.我希望能够根据第一个模型对第二个模型进行排序.我认为下面的代码示例可以最好地说明我想要实现的目标.
I have two Django models, in which the one refers to the other. I want to be able to sort the second model based on the first. I think the code example below illustrates best what I want to achieve.
class Record(models.Model):
uuid = models.CharField(max_length=32)
code = models.CharField(max_length=32)
class Meta:
ordering = ['code']
class Article(models.Model):
code = models.CharField(max_length=32)
def get_sorted_submodels(self):
return sorted(self.submodels.all(), key=Submodel.key_sorting)
class Submodel(models.Model):
code = models.CharField(max_length=32)
article = models.ForeignKey(Article, related_name='submodels')
record_uuid = models.CharField(max_length=32)
@property
def record(self):
return Record.objects.get(uuid=self.record_uuid)
@staticmethod
def key_sorting(obj):
return (obj.record, obj.code)
如果现在调用方法get_sorted_submodels
,则会出现以下错误:
If I now call the method get_sorted_submodels
, I get the following error:
TypeError: unorderable types: Record() < Record()
我已经在模型Record上实现了字段排序.
I already implemented the field ordering on model Record.
- 如何使该模型可排序,以便可以使用此排序 机制?
- 如果这不可能,是否还有另一种好方法 启用先按记录"排序,然后再按其自身的代码排序?
- How can I make this model orderable such that I can use this sorting mechanism?
- If that is not possible, is there another good way to enable sorting on Record first, and then on its own code?
PS:我明确不想在Submodel类上使用class Meta
和ordering
,因为这基本上是仅在此上下文中使用的第二顺序.
PS: I explicitly do not want to use class Meta
and ordering
on Submodel class, since this is basically a second ordering only used in this context.
推荐答案
ordering
元字段仅控制在数据库查询中对记录进行排序的方式. sorted
是Python函数,与此完全无关.
The ordering
Meta field only controls how records are sorted in database queries. sorted
is a Python function and completely unrelated to this.
要使Record
实例在Python中可排序,可以给他们提供__lt__
方法:
To make Record
instance sortable in Python, you can give them a __lt__
method:
def __lt__(self, other):
return self.code < other.code
现在Python可以对它们进行排序了,您的错误将消失.但是最好让数据库来做,所以根本不要使用sorted
:
Now Python can sort them, and your error will be gone. But it's better to let the database do it, so don't use sorted
at all:
def get_sorted_submodels(self):
return self.submodels.order_by('record__code')
要在编辑后执行此操作,我将更改方法(从django.utils.decorators导入cached_property):
to do it after your edit, I'd change the methods like so (import cached_property from django.utils.decorators):
@cached_property
def record(self):
return Record.objects.get(uuid=self.record_uuid)
@staticmethod
def key_sorting(obj):
return (obj.record.code, obj.code)
这篇关于在Django模型上定义排序键的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!