簡體   English   中英

Django order_by 不是查詢結果的排序

[英]Django order_by is not ordering results of query

Django 未按日期排序結果。 我正在使用 Django-Rest-Framework 創建 API 應用程序最初在查詢中有一個過濾器,在閱讀了類似的問題后,人們在結合 order_by 和過濾器時遇到了同樣的問題,我刪除了過濾器並使用 for 循環手動過濾,但仍然得到相同的結果。

最初查詢是:

progresslogs = ProgressLog.objects.filter(user__userprofile__coach=request.user).order_by('-date')

但是閱讀類似的問題我改變了查詢並手動過濾認為一起使用過濾器和排序有問題但我仍然得到亂序的結果:

class ProgressLogAPI(APIView):
    def get(self, request: Request, format=None):
        if request.user.is_authenticated:
            if request.user.is_staff:
                logger.info('API: Staff {} fetched progress logs'.format(request.user.id))
                progresslogs = ProgressLog.objects.order_by('-date')
                # Below loop added to manually filter results
                filteredlogs = []
                for progress in progresslogs:
                    if progress.user.userprofile.coach == request.user:
                        filteredlogs.append(progress)

                serializer = ProgressLogSerializer(filteredlogs, many=True)
                return Response(data=serializer.data)

但在每種情況下,結果都是亂序的,想知道這是 Django 中的一些錯誤,我想可能可以手動對結果進行排序,但我認為這會大大增加 API 調用獲取結果的時間,所以不要真的想這樣做。

作為參考,下面是 API 調用的前 3 個結果,其中不適用的數據被替換為 aa '?' 但可以從根本沒有訂購的日期值中清楚地看出:

[
  {
    "id":?,
    "user":?,
    "front_pic":"?",
    "side_pic":"?",
    "back_pic":"?",
    "weight":"?",
    "date":"2022-04-30",
    "bicep":null,
    "chest":null,
    "legs":null,
    "waist":null,
    "body_fat":null
  },
  {
     "id":?,
     "user":?,
    "front_pic":"?",
    "side_pic":"?",
    "back_pic":"?",
    "weight":"?",
    "date":"2022-03-27",
    "bicep":null,
    "chest":null,
    "legs":null,
    "waist":null,
    "body_fat":null
  },
  {
    "id":?,
    "user":?,
    "front_pic":"?",
    "side_pic":"?",
    "back_pic":"?",
    "weight":"?",
    "date":"2022-05-22",
    "bicep":null,
    "chest":null,
    "legs":null,
    "waist":null,
    "body_fat":null
  },
  ...
]

服務器上的 Django 版本是3.2.13和 python 版本是3.9

編輯:這里要求的是 model 和序列化:

Model:

class ProgressLog(models.Model):
    user = models.ForeignKey(User, on_delete=models.CASCADE)
    front_pic = models.ImageField(upload_to='progress_front', blank=True)
    side_pic = models.ImageField(upload_to='progress_side', blank=True)
    back_pic = models.ImageField(upload_to='progress_back', blank=True)
    weight = models.DecimalField(blank=True, decimal_places=1, max_digits=6)
    date = models.DateField(default=get_date)
    body_fat = models.DecimalField(blank=True, decimal_places=1, max_digits=4, null=True)
    waist = models.IntegerField(blank=True, null=True)
    bicep = models.IntegerField(blank=True, null=True)
    chest = models.IntegerField(blank=True, null=True)
    legs = models.IntegerField(blank=True, null=True)

    def __str__(self):
        return '{} | {}'.format(self.user.username, self.date)

序列化器:

class ProgressLogSerializer(serializers.ModelSerializer):
    class Meta:
        model = ProgressLog
        fields = ['id', 'user', 'front_pic', 'side_pic', 'back_pic', 'weight', 'date', 'bicep', 'chest', 'legs', 'waist',
                  'body_fat']

自從昨晚發布問題以來,我嘗試將 Django 更新到版本4.0.2 ,以防 Django 的特定版本中存在任何錯誤導致此問題,但結果仍然沒有按日期字段排序。

還通過在服務器上的 Django shell `python manage.py shell' 中查詢進行檢查,本例中的結果是有序的:

>>> from progress_logger.models import ProgressLog
>>> ProgressLog.objects.all().order_by('-date')[:3]
<QuerySet [<ProgressLog: ? | 2022-05-24>, <ProgressLog: ? | 2022-05-23>, <ProgressLog: ? | 2022-05-23>]>

無法按照我想要的方式解決它,但使用 ListViewAPI 似乎已經解決了它,猜測問題可能與 Django-rest-framework 有關,因為交互式 shell 的結果如預期的那樣:

class ProgressLogAPI(ListAPIView):
    permission_classes = [IsAdminUser]
    queryset = ProgressLog.objects.filter(user__userprofile__coach=request.user).order_by('-date')
    serializer_class = ProgressLogSerializer

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM