Code

Opened 22 months ago

Last modified 22 months ago

#19018 new Bug

m2m relationships with a through field don't respect types.

Reported by: justinlilly Owned by: nobody
Component: Database layer (models, ORM) Version: 1.4
Severity: Normal Keywords:
Cc: Triage Stage: Accepted
Has patch: no Needs documentation: no
Needs tests: no Patch needs improvement: no
Easy pickings: no UI/UX: no

Description

I ran into an issue today in which an empty list was returned from a Queryset when it should have been a blatant failure.

Given the models in https://github.com/django/django/blob/master/tests/modeltests/m2m_through/models.py

The following returns an empty queryset:

  Group.objects.filter(members__in=[Friendship(pk=9)])

Attachments (0)

Change History (6)

comment:1 Changed 22 months ago by justinlilly

  • Needs documentation unset
  • Needs tests unset
  • Patch needs improvement unset
  • Type changed from Uncategorized to Bug

comment:2 Changed 22 months ago by Alex

  • Triage Stage changed from Unreviewed to Accepted

comment:3 Changed 22 months ago by carljm

I don't believe this bug is specific to m2ms or through models at all. In general, currently you can pass any iterable of instances of any model to any __in query and the ORM will happily use the PKs of the models you give it, without checking whether they are an instance of the right model class (or a subclass, or raw PK values which is also supported).

comment:4 Changed 22 months ago by carljm

(Also not specific to __in queries, same is true of a simple __exact match on an FK field).

comment:5 Changed 22 months ago by Alex

Everything you just said is correct, it's not just your belief :)

comment:6 Changed 22 months ago by ptone

So looking at this mostly for my own edification.

A higher level place this could be checked would be db.models.where.Constraint.process

otherwise: db.models.fields.related.RelatedField.get_db_prep_lookup and db.models.fields.related.RelatedField._pk_trace

seem like the best places to tackle this.

However unless a patch is pretty quick, it seems worth improving the docs, at least in the interim, to clarify that lookup values for model instances will always be converted to a simple pk value for database lookups.

Add Comment

Modify Ticket

Change Properties
<Author field>
Action
as new
The owner will be changed from nobody to anonymous. Next status will be 'assigned'
as The resolution will be set. Next status will be 'closed'
Author


E-mail address and user name can be saved in the Preferences.

 
Note: See TracTickets for help on using tickets.