在同一视图中使用来自django查询的数据

时间:2021-04-22 01:04:22

I might have missed somthing while searching through the documentation - I can't seem to find a way to use data from one query to form another query.

在搜索文档时我可能错过了一些东西 - 我似乎找不到使用一个查询中的数据来形成另一个查询的方法。

My query is:

我的查询是:

sites_list = Site.objects.filter(worker=worker)

I'm trying to do something like this:

我正在尝试做这样的事情:

for site in sites_list:
    [Insert Query Here]

Edit: I saw the awnser and im not sure how i didnt get that, maybe thats the sign im up too late coding :S

编辑:我看到了awnser,我不知道我怎么没有得到那个,也许这就是我太晚编码的标志:S

2 个解决方案

#1


You could easily do something like this:

您可以轻松地执行以下操作:

sites_list = Site.objects.filter(worker=worker)

for site in sites_list:
    new_sites_list = Site.objects.filter(name=site.name).filter(something else)

#2


You can also use the __in lookup type. For example, if you had an Entry model with a relation to Site, you could write:

您还可以使用__in查找类型。例如,如果您有一个与Site关系的Entry模型,您可以编写:

Entry.objects.filter(site__in=Site.objects.filter(...some conditions...))

This will end up doing one query in the DB (the filter condition on sites would be turned into a subquery in the WHERE clause).

这将最终在DB中执行一个查询(站点上的过滤条件将转换为WHERE子句中的子查询)。

#1


You could easily do something like this:

您可以轻松地执行以下操作:

sites_list = Site.objects.filter(worker=worker)

for site in sites_list:
    new_sites_list = Site.objects.filter(name=site.name).filter(something else)

#2


You can also use the __in lookup type. For example, if you had an Entry model with a relation to Site, you could write:

您还可以使用__in查找类型。例如,如果您有一个与Site关系的Entry模型,您可以编写:

Entry.objects.filter(site__in=Site.objects.filter(...some conditions...))

This will end up doing one query in the DB (the filter condition on sites would be turned into a subquery in the WHERE clause).

这将最终在DB中执行一个查询(站点上的过滤条件将转换为WHERE子句中的子查询)。