Cannot update a query once a slice has been taken

后端 未结 6 698
南笙
南笙 2020-12-09 02:51

I am trying to do this:

UserLog.objects.filter(user=user).filter(action=\'message\').filter(timestamp__lt=now)[0:5].update(read=True)

but I

6条回答
  •  时光取名叫无心
    2020-12-09 03:29

    If you want to slice out some of the results of a queryset, you can copy it it to another variable (a shallow copy is enough, which is faster than a deep copy because it just uses references to the original objects.)

    import copy
    
    queryset = Mytable.objects.all()
    pieceOfQuery = copy.copy(queryset)
    pieceOfQuery = pieceOfQuery[:10]
    

    This will keep Django from complaining if you have an order_by filter on your table, since that happens after the slicing if you do it on the main queryset object

提交回复
热议问题