Opened 6 years ago

Closed 2 years ago

#14003 closed Bug (fixed)

Filtering on a relation whose model has a different PK type doesn't work

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

Description

Using the following models:

class Author(models.Model):
    name = models.CharField(max_length=255)

class Book(models.Model):
    name = models.CharField(max_length=50, primary_key=True)
    author = models.ForeignKey(Author)

The following code fails:

In [1]: a = Author.objects.create(name='Me')

In [2]: b = Book.objects.create(name='My Book', author=a)

In [3]: Author.objects.filter(book=b)
....
ValueError: invalid literal for int() with base 10: 'My Book'

This seems to be the source of the problem:

http://code.djangoproject.com/browser/django/trunk/django/db/models/fields/related.py?rev=13037#L190

_pk_trace uses field.rel.to to resolve the field to use for prepping the filter value. In the case above, It's preparing Book.pk (a CharField) as if it were a value for Author.pk (an AutoField) and blows up when casting the string to an int. I'm not sure how best to go about solving the issue. _pk_trace doesn't currently have any way I know of to tell which side of the relation the value arg is coming from.

Attachments (1)

14003-testcase.patch (1.8 KB) - added by Aymeric Augustin 5 years ago.

Download all attachments as: .zip

Change History (7)

comment:1 Changed 6 years ago by David Gouldin

Cc: dgouldin@… added
Needs documentation: unset
Needs tests: unset
Patch needs improvement: unset

I actually found this while researching a fix for #13383. I don't think that ticket can be properly fixed until this one is resolved.

comment:2 Changed 6 years ago by Karen Tracey

Resolution: duplicate
Status: newclosed

I believe this is the same root problem as what is described in #11319.

comment:3 Changed 5 years ago by Ole Laursen

Easy pickings: unset
Resolution: duplicate
Severity: Normal
Status: closedreopened
Type: Bug
UI/UX: unset

The fix for 11319 unfortunately didn't fix this. :( I have this problem 1.2.7 and 1.3.1. This is a regression from 1.1.1 which works fine.

Changed 5 years ago by Aymeric Augustin

Attachment: 14003-testcase.patch added

comment:4 Changed 5 years ago by Aymeric Augustin

Triage Stage: UnreviewedAccepted

I can confirm the problem. I'm attaching a test case. The tests fails with trunk; but if I remove , foreign_key=True in the definition of the Book model, it passes.

comment:5 Changed 4 years ago by Aymeric Augustin

Status: reopenednew

comment:6 Changed 2 years ago by Olivier Le Thanh Duong

Resolution: fixed
Status: newclosed

Look's like this was fixed in 97774429aeb54df4c09895c07cd1b09e70201f7d

Note: See TracTickets for help on using tickets.
Back to Top