我正在开发一个在模型中具有两个通用关系的项目。我发现这些关系是无用的,而且还有300万条我们不再需要的记录。有没有办法快速删除它?
删除迁移字段无效,因为它是通用的。
所以我试过
import time
from django.contrib.contenttypes.models import ContentType
from app.core import models as m
# UserInformation has a GenericRelation with Address
c = m.UserInformation.objects.first()
c_type = ContentType.objects.get_for_model(c)
# get all the models records generic related with UserInformation
query = m.Address.objects.filter(content_type_id=c_type.id)
start = time.time()
i=0
stop_iteration = 10
for user in query:
i += 1
user.delete()
if i == stop_iteration:
break
end = time.time()
seconds = end - start
print('Execution of %s deletes: %3d seconds' % (stop_iteration, seconds))
结果:
Execution of 10 deletes: 34 seconds
这意味着删除约1百万条记录需要37天
有没有办法更快地做到这一点?
答案 0 :(得分:1)
通用关系由content_type
和object_id
定义。如果您知道content_type
,则可以找到所有object_id
值并在一个查询中将其删除。我不知道你的模型中的字段,但它应该是这样的。
# get all related object ids
object_ids = m.Address.objects.filter(content_type_id=c_type.id)\
.values_list('object_id', flat=True)
# delete them in one query
YourModel.objects.filter(id__in=object_ids).delete()