如何优化 ORM 查询以获得更快的结果?

How do I optimize ORM queries for faster results?

我在 table 日历中有 80k+ 个条目。当我 运行 以下两种方法中的任何一种时,过滤器或 get 执行时间太长,并且由于服务器在一段时间后崩溃并且没有添加新条目。我想知道是否有更多的方法可以解决这个问题。

方法一:

date_list = []
d1 = date(2022, 5, 1)
d2 = date(2022, 6, 30)
delta = d2 - d1
for i in range(delta.days + 1):
    date_list.append(d1 + timedelta(days=i))
profiles = Profile.objects.all()
for j in date_list:
    for i in profiles:
        try:
            Calendar.objects.get(date=j,emp_id = i.emp_id)
        except Calendar.DoesNotExist:
            e = Calander()
            e.team = i.emp_process
            e.date = j
            e.emp_name = i.emp_name
            e.emp_id = i.emp_id
            e.emp_desi = i.emp_desi
            e.att_actual = "Unmarked"
            e.save()

方法二:

date_list = []
d1 = date(2022, 5, 1)
d2 = date(2022, 6, 30)
delta = d2 - d1
for i in range(delta.days + 1):
    date_list.append(d1 + timedelta(days=i))
profiles = Profile.objects.all()

for j in date_list:
    for i in profiles:
        cal = Calander.objects.filter(date=j,emp_id = i.emp_id).count()
        if cal < 1:
            e = Calander()
            e.team = i.emp_process
            e.date = j
            e.emp_name = i.emp_name
            e.emp_id = i.emp_id
            e.emp_desi = i.emp_desi
            e.att_actual = "Unmarked"
            e.save()

试试这个:

date_list = []
d1 = date(2022, 5, 1)
d2 = date(2022, 6, 30)
delta = d2 - d1
for i in range(delta.days + 1):
    date_list.append(d1 + timedelta(days=i))

for j in date_list:
    profiles = Profile.objects.exclude(emp_id__in=Calendar.objects.filter(date=j).values('emp_id'))
    calendars = []
    for i in profiles:
        e = Calendar()
        e.team = i.emp_process
        e.date = j
        e.emp_name = i.emp_name
        e.emp_id = i.emp_id
        e.emp_desi = i.emp_desi
        e.att_actual = "Unmarked"
        calendars.append(e)
    Calendar.objects.bulk_create(calendars)