Django ORM 中的`difference()` 之后的`delete()`
`delete()` after `difference()` in Django ORM
问题是关于 Django ORM 中 difference()
之后的 delete()
。
我的目标是当数据库中的记录量大于特定数量时删除旧模型实例。
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')
计划:
- 构建包含所有条目的查询集。
- 使用要保留的条目构造查询集。
- 计算差值
- 删除其余部分。
现实:
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
是bug还是我没看懂?
StatusLog.objects.filter(id__in=list(StatusLog.objects.values_list('pk', flat=True)[:N])).delete()
工作起来很有魅力
问题是关于 Django ORM 中 difference()
之后的 delete()
。
我的目标是当数据库中的记录量大于特定数量时删除旧模型实例。
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')
计划:
- 构建包含所有条目的查询集。
- 使用要保留的条目构造查询集。
- 计算差值
- 删除其余部分。
现实:
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
是bug还是我没看懂?
StatusLog.objects.filter(id__in=list(StatusLog.objects.values_list('pk', flat=True)[:N])).delete()
工作起来很有魅力