删除Django查询中的重复项。我使用select_related并将请求数量从90个减少到18个,但是如果数据库增长,那么这并不能拯救我。如何改进查询?
views.py
def index(request):
snj = ScheduleNotJob.objects.select_related()
form = SNJ()
return render(request,"index.html",{'snj': snj, 'form':form})
models.py
class Office(models.Model):
title = models.CharField(max_length=150, db_index=True)
def __str__(self):
return self.title
class Post(models.Model):
office = models.ForeignKey(Office, on_delete=models.CASCADE)
title = models.CharField(max_length=150, db_index=True)
def __str__(self):
return self.title
class Human(models.Model):
office = models.ForeignKey(Office, on_delete=models.CASCADE)
post = ChainedForeignKey(
Post,
chained_field="office",
chained_model_field="office",
show_all=False,
)
initials = models.CharField(max_length=150, db_index=True)
def __str__(self):
return self.initials
class Reason(models.Model):
title = models.CharField(max_length=150)
def __str__(self):
return self.title
class Shift(models.Model):
title = models.CharField(max_length=150)
def __str__(self):
return self.title
class ScheduleNotJob(models.Model):
shift = models.ForeignKey(Shift, on_delete=models.CASCADE)
office = models.ForeignKey(Office, on_delete=models.CASCADE)
post = GroupedForeignKey(Post, "office")
human = GroupedForeignKey(Human, "post")
reason = models.ForeignKey(Reason, on_delete=models.CASCADE)
comment = models.CharField(max_length=300, blank=True, null=True)
length_time = models.IntegerField(blank=True, null=True)
date_start = models.DateField(blank=True, null=True)
date_end = models.DateField(blank=True, null=True)
index.html
{% for elem in snj %}
<tr class="mySelect">
<td>{{ elem.id }}</td>
<td>{{ elem.shift }}</td>
<td>{{ elem.office }}</td>
<td>{{ elem.post }}</td>
<td>{{ elem.human }}</td>
<td>{{ elem.reason }}</td>
<td>{{ elem.comment }}</td>
{% endfor %}
我使用select_related并将请求数量从90个减少到18个,但是如果数据库增长,那么这将无法拯救我。如何改进查询?
您可以使用Only()方法并传递所需的字段,这些字段在计算查询集时立即加载。
def index(request):
snj = ScheduleNotJob.objects.select_related(
'shift', 'office', 'post', 'human'
).only(
'id', 'reason', 'comment', 'shift_id', 'shift__title', 'office_id', 'office__title', 'post_id', 'post__title', 'human_id', 'human__initials'
)
form = SNJ()
return render(request,"index.html",{'snj': snj, 'form':form})
my_list = [1, 2, 3, 3, 4, 5, 5]
my_list = list(set(my_list))
print(my_list) # prints [1, 2, 3, 4, 5]
如果你有一个包含重复项的列表或其他集合,你可以使用Python内置的set()函数来删除重复项。