如何删除django请求中的重复项

gk7wooem  于 2023-04-13  发布在  Go
关注(0)|答案(2)|浏览(150)

删除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,但如果数据库增长,那么这不会保存我。如何改进查询?

pobjuy32

pobjuy321#

您可以使用**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})
3zwtqj6y

3zwtqj6y2#

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()函数来删除重复项。

相关问题