Django:按照多对多的关系排序 [英] Django: order by field of many-to-many relation
本文介绍了Django:按照多对多的关系排序的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
class A(models.Model):
things = models。 ManyToManyField('B')
class B(models.Model):
score = models.FloatField()
text = models.CharField(max_length = 100)
如何获取 A
c
解决方案
如果我明白你的意思,应该这样做。 列表
将包含由每个对象的最高得分内容的文本排序的模型A的所有对象的列表。
dict = {}
list = []
在A.objects.all()中:
dict [a] = a.things。 all()。order_by( - score)[0] .text
for k,v in sorted(dict.items(),key = lambda x:x [1]):
list。 append(k)
可能写一个更漂亮的方式,但是我不能想到一个在我头顶...
Given django models A and B:
class A(models.Model):
things = models.ManyToManyField('B')
class B(models.Model):
score = models.FloatField()
text = models.CharField(max_length=100)
How do I get a list of A
entities ordered by the text
of the highest-scoring B
in things
?
解决方案
If I understand you correctly, this should do it. list
will contain a list of all the objects of model A sorted by the text of each object's highest scoring thing.
dict = {}
list = []
for a in A.objects.all():
dict[a] = a.things.all().order_by("-score")[0].text
for k, v in sorted(dict.items(), key=lambda x: x[1]):
list.append(k)
There might be a prettier way to write it, but I can't think of one off the top of my head...
这篇关于Django:按照多对多的关系排序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文