如何确保保留此订单

2024-10-04 07:35:21 发布

您现在位置:Python中文网/ 问答频道 /正文

我想知道什么是确保保留此顺序的最佳方法,我认为最好的方法是应用一个动态操作的函数,当sqlite保留顺序时,postgres不会在保存到数据库时对其进行重新排序

list_of_dicts = [[{'id': '3', 'text': ' Perpetual ', 'score': 3}, {'id': '2', 'text': ' Peter Parker ', 'score': 2}, {'id': '1', 'text': ' Miles .T Morales ', 'score': 1}], [{'id': '3', 'text': 'Perpetual ', 'score': 3}, {'id': '1', 'text': 'Miles .T Morales ', 'score': 2}, {'id': '2', 'text': 'Peter Parker ', 'score': 1}], [{'id': '1', 'text': 'Miles .T Morales ', 'score': 3}, {'id': '3', 'text': 'Perpetual ', 'score': 2}, {'id': '2', 'text': 'Peter Parker ', 'score': 1}], [{'id': '3', 'text': ' Perpetual ', 'score': 3}, {'id': '2', 'text': ' Peter Parker ', 'score': 2}, {'id': '1', 'text': ' Miles .T Morales ', 'score': 1}], [{'id': '1', 'text': ' Miles .T Morales ', 'score': 3}, {'id': '2', 'text': ' Peter Parker ', 'score': 2}, {'id': '3', 'text': ' Perpetual ', 'score': 1}], [{'id': '2', 'text': ' Peter Parker ', 'score': 3}, {'id': '3', 'text': ' Perpetual ', 'score': 2}, {'id': '1', 'text': ' Miles .T Morales ', 'score': 1}]]

我想从最高分数到最低分数对列表进行排序,但不依赖于数据库

编辑

我使用django models.JSONField来存储数据。将queryset.order\u by('data\u score')添加到视图中时对其没有影响。 模型也是如此。元排序属性

.....
class Meta:
    ordering = ("data__score",)

没有效果,我认为这与数据库有关,现在我只想知道如何使用python对其排序,而不是依赖于数据库/ORM不一致性

编辑2

我的模型:

class Ballot(models.Model):
    user = models.ForeignKey(User, on_delete=models.CASCADE)
    election = models.ForeignKey(
        Election, related_name="ballots", on_delete=models.CASCADE
    )
    data = models.JSONField(null=True)
    cast_date = models.DateTimeField(auto_now_add=True)
    updated = models.DateTimeField(auto_now=True)

Tags: 方法textid数据库truedata排序顺序
1条回答
网友
1楼 · 发布于 2024-10-04 07:35:21

我能够通过python排序和函数属性来解决这个问题

model_ballot = ModelBallot.objects.filter(
    election__id__exact=election_id
).values_list("data", flat=True)

new_model_ballot = []
ballots = list()
for b in model_ballot:
    newlist = sorted(b, key=lambda k: k['score'], reverse=True)
    new_model_ballot.append(newlist)

相关问题 更多 >