删除Django查询Image SQL duplicate中的重复项。我使用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,但如果数据库增长,那么这不会保存我。如何改进查询?
2条答案
按热度按时间pobjuy321#
您可以使用**Only()**方法并传递必填字段,这些字段将在计算查询集时立即加载。
3zwtqj6y2#
如果你有一个列表或其他包含重复项的集合,你可以使用Python内置的set()函数来删除重复项。