Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Fixed #26196 -- Made sure __in lookups use to_field as default. #6111

Closed
wants to merge 1 commit into from
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
10 changes: 10 additions & 0 deletions django/db/models/fields/related_lookups.py
Expand Up @@ -79,6 +79,16 @@ def as_sql(self, compiler, connection):
[source.name for source in self.lhs.sources], self.rhs),
AND)
return root_constraint.as_sql(compiler, connection)
elif not self.rhs_is_direct_value():
from django.db.models.sql.where import WhereNode, SubqueryConstraint, AND, OR
root_constraint = WhereNode(connector=OR)
root_constraint.add(
SubqueryConstraint(
self.lhs.alias, [self.lhs.target.column],
[f.get_attname_column()[1] for f in self.lhs.output_field.get_path_info()[0].target_fields],
Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

@akaariai I'm really not sure from where I should retrieve the SubqueryConstraint.targets. I see that self.lhs.sources is available when isinstance(self.lhs, MultiColSource) but in this case self.lhs.sources is an empty list.

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I'm going to try to work on Django tomorrow. I'll try to work on this.

self.rhs),
AND)
return root_constraint.as_sql(compiler, connection)
else:
return super(RelatedIn, self).as_sql(compiler, connection)

Expand Down
12 changes: 12 additions & 0 deletions tests/queries/tests.py
Expand Up @@ -2416,6 +2416,18 @@ def test_in_query(self):
{lunch, dinner},
)

def test_in_subquery(self):
apple = Food.objects.create(name="apple")
lunch = Eaten.objects.create(food=apple, meal="lunch")
self.assertEqual(
set(Eaten.objects.filter(food__in=Food.objects.filter(name='apple'))),
{lunch},
)
self.assertEqual(
set(Eaten.objects.filter(food__in=Food.objects.filter(name='apple').values('eaten__meal'))),
set(),
)

def test_reverse_in(self):
apple = Food.objects.create(name="apple")
pear = Food.objects.create(name="pear")
Expand Down