Django Delete all but last five of queryset

后端 未结 3 1283
[愿得一人]
[愿得一人] 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 09:49

    this is how i ended up doing this.

        notes = Notification.objects.filter(user=self.user)
        for note in notes[4:]:
            note.delete()
    

    because i'm doing this in the save method, the only way the loop would ever have to run more than once would be if the user got multiple notifications at once. i'm not worried about that happening (while it may happen it's not likely to be enough to cause a problem).

提交回复
热议问题