Django Delete all but last five of queryset

后端 未结 3 1285
[愿得一人]
[愿得一人] 2020-12-13 09:33

I have a super simple django model here:

class Notification(models.Model):
    message = models.TextField()
    user = models.ForeignKey(User)
    timestamp          


        
3条回答
  •  被撕碎了的回忆
    2020-12-13 10:10

    Use an inner query to get the set of items you want to keep and then filter on them.

    objects_to_keep = Notification.objects.filter(user=user).order_by('-created_at')[:5]
    Notification.objects.exclude(pk__in=objects_to_keep).delete()
    

    Double check this before you use it. I have found that simpler inner queries do not always behave as expected. The strange behavior I have experienced has been limited to querysets that are just an order_by and a slice. Since you will have to filter on user, you should be fine.

提交回复
热议问题