I have some problem. Consider this data schema in DB (for simplicity I omit some things):
class Table1(Model):
field1;
field2;
table2 = ForeignKey('Table2');
class Table2(Model):
filed3;
Now sample data:
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 }
And main part:
SQL query:
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%';
Will result in two rows form Table1: id=1 and id=2.
Now I would like the same from django but when i try:
Table1.objects.filter( Q(filed1__icontains="lola") | Q(table2__filed3__icontains="lola") );
it returns only id=1 because table2_id is null on row with id=2.
It excludes row with id=2 because it fails on second Q. How can I get two rows from Django in that case?
Any ideas?
As I understand, the database schema is created not by means of django-orm. In your case Django make INNER JOIN
. Use:
table2 = ForeignKey('Table2', blank=True, null=True)