`delete()` after `difference()` in Django ORM

Viewed 113

Question is regarding delete() after difference() in Django ORM.

My goal here is to delete old model instances when amount of record in db greater then certain number.

class StatusLog(models.Model):
    logger_name = models.CharField(max_length=100)
    level = models.PositiveSmallIntegerField(choices=LOG_LEVELS, default=logging.ERROR, db_index=True)
    msg = models.TextField()
    trace = models.TextField(blank=True, null=True)
    create_datetime = models.DateTimeField(auto_now_add=True, verbose_name='Created at')

Plan:

  1. construct queryset with all entries.
  2. construct queryset with entries to keep.
  3. calculate difference
  4. delete rest.

Reality:

a = StatusLog.objects.all().order_by('pk')
a.count() = 93
# as planed

b = StatusLog.objects.all().order_by('pk')[:50]
b.count() = 50
# as planed

c = a.difference(b)
c.count() = 43
# as planed

c.update(trace='test') 
# returns 93. Updated whole table.
# WTF?????? Should be 43

Is it a bug or I don’t understand something?

1 Answers
StatusLog.objects.filter(id__in=list(StatusLog.objects.values_list('pk', flat=True)[:N])).delete()

Works like charm

Related