简体   繁体   English

使用 django 模型进行复杂查询

[英]Making complex query with django models

I created a view in my database model with 6 joins and 10 columns, and at the moment it shows around 86.000 rows.我在我的数据库 model 中创建了一个视图,其中包含 6 个连接和 10 列,目前它显示了大约 86.000 行。 I try to query all the rows by objects.all() and then filter according to user interaction (form data sent by POST and then choosing appropriate.filter(*args) querying) After that I tried to get the length of the queryset by using count() since this method doesnt evaluate the query.我尝试通过 objects.all() 查询所有行,然后根据用户交互进行过滤(POST 发送的表单数据,然后选择适当的.filter(*args) 查询)之后我尝试通过以下方式获取查询集的长度使用 count() 因为此方法不评估查询。 But since views don't have indexes on the columns, the count() method takes to long.但是由于视图在列上没有索引,所以 count() 方法需要很长时间。

I searched for the solution of materializing the view but that isn't possible in mysql.我搜索了实现视图的解决方案,但这在 mysql 中是不可能的。

Then I searched for a solution that might be able to replace the initial.all() by just using the 6 joins and filtering arguments in django rather than creating a view, so the indexes would still be available.然后我搜索了一个解决方案,它可能能够通过仅使用 6 个连接并在 django 中过滤 arguments 而不是创建视图来替换 initial.all(),因此索引仍然可用。 But I couldn't find a solution to that problem.但我找不到该问题的解决方案。

Or maybe combining every row from the view with another table so I can use the index of the other table for faster querying?:或者也许将视图中的每一行与另一个表结合起来,这样我就可以使用另一个表的索引来更快地查询?:

SELECT * FROM View LEFT JOIN Table ON (View.id = Table.id)

I appreciate every answer我感谢每一个答案

Try this below:在下面试试这个:

from django.db import models

# I think below is your table structure
class Table(models.Model):
    pass

class View(models.Model):
    table = models.ForeignKey(to=Table)

qs = View.objects.select_related('table').filter(table__isnull=True)
for iterator in qs:
    print(qs)

Thanks !谢谢 !

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM