python - Django、ForeignKey 关系和 Q 或

标签 python django django-models relation django-q

我有一些问题。考虑 DB 中的这个数据模式(为简单起见,我省略了一些东西):

class Table1(Model):
   field1;
   field2;
   table2 = ForeignKey('Table2');

class Table2(Model):
   filed3;

现在示例数据:

Table2:
{ id:1, field3: lola }
{ id:2, field3: disney }

Table1:
{ id:1, field1: foo, field2: bar, table2_id: 1 }
{ id:2, field1: lola, field2: bars, table2_id: null }

主要部分:

SQL查询:

SELECT t1.*, t2.field3 
FROM table1 AS t1 LEFT JOIN table2 AS t2 ON t1.table2_id=t2.id 
WHERE t1.field1 ILIKE '%lola%' OR t2.field3 ILIKE '%lola%';

将从 Table1 中生成两行:id=1 和 id=2。

现在我想从 django 得到同样的东西,但是当我尝试时:

Table1.objects.filter( Q(filed1__icontains="lola") | Q(table2__filed3__icontains="lola") );

它只返回 id=1,因为 table2_id 在 id=2 的行上为空。

它排除了 id=2 的行,因为它在第二个 Q 上失败了。 在这种情况下,如何从 Django 获取两行?

有什么想法吗?

最佳答案

据我了解,数据库模式不是通过 django-orm 创建的。在你的例子中,Django 使 INNER JOIN。使用:

table2 = ForeignKey('Table2', blank=True, null=True)

关于python - Django、ForeignKey 关系和 Q 或,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12800529/

相关文章:

python - 如何在 Neovim 中使用 Python 语言服务器协议(protocol)

python - 如何在 pygame 中的幻灯片之间切换

python - 使用 scrapy 从 wordpress 站点抓取

python - django模板显示项目值或空字符串

python /Django : Are there any decorators to tell that input is not none?

Python matplotlib/seaborn 绘图条形图子类别

python - django没有名为article.models的模块

django - 记录所有 django 模型中的所有保存/更新/删除操作

python - 基于 Django 模型内部方法的计算字段

使用 F 和 Q 表达式过滤 Django 模型