#35697: Filtering on a ForeignKey relation with the field it relates to is not
possible
-------------------------------------+-------------------------------------
     Reporter:  Petter Friberg       |                     Type:  Bug
       Status:  new                  |                Component:  Database
                                     |  layer (models, ORM)
      Version:  5.0                  |                 Severity:  Normal
     Keywords:                       |             Triage Stage:
                                     |  Unreviewed
    Has patch:  0                    |      Needs documentation:  0
  Needs tests:  0                    |  Patch needs improvement:  0
Easy pickings:  0                    |                    UI/UX:  0
-------------------------------------+-------------------------------------
 My use case is that I have a `ForeignKey` relation with `constraint=False`
 and then want to use `rel_id=models.F("rel__pk")` to ensure that the value
 indeed exists in the related table.

 Example:

 {{{
 #!python
 from django.db import models

 class A(models.Model):
     ...

 class B(models.Model):
     a = models.ForeignKey(A, on_delete=models.CASCADE, constraint=False)


 B.objects.filter(a_id=models.F("a__pk"))
 }}}

 Here I would (optimally) want/expect the SQL to look like, though I would
 suspect that would have to be quite special cased:

 {{{
 #!sql
 SELECT "app_b"."id", "app_b"."a_id" FROM "app_b" INNER JOIN "app_a" ON
 ("app_b"."a_id" = "app_a"."id")
 }}}

 What I'm actually getting, I'm guessing that Django tries to be a bit too
 "smart" when resolving `"a__pk"` here:

 {{{
 #!sql
 SELECT "app_b"."id", "app_b"."a_id" FROM "app_b" WHERE "app_b"."a_id" =
 ("app_b"."a_id")
 }}}

 Though I can get my `INNER JOIN` by adding a `.select_related` call. If I
 also pair that with calling e.g. `.only` I can minimise the additional
 impact of the join. But I still thought it was worth filing this as I
 figured it was quite unexpected that `"a__pk"` was resolved to
 `"app_b"."a_id"` in this situation.

 Note: I get the same SQL output when passing the primary key field
 explicitly, `F("a__id")` in this case, instead of `pk`.
-- 
Ticket URL: <https://code.djangoproject.com/ticket/35697>
Django <https://code.djangoproject.com/>
The Web framework for perfectionists with deadlines.

-- 
You received this message because you are subscribed to the Google Groups 
"Django updates" group.
To unsubscribe from this group and stop receiving emails from it, send an email 
to django-updates+unsubscr...@googlegroups.com.
To view this discussion on the web visit 
https://groups.google.com/d/msgid/django-updates/0107019171631f44-c5c2f8f1-47e4-4db8-98e1-6e6d61aa2b4d-000000%40eu-central-1.amazonses.com.

Reply via email to