Opened 5 years ago

Closed 5 years ago

#30627 closed Bug (fixed)

In multi-table inheritance, querying with invalid pk raises different exception depending on the inheritance level.

Reported by: Antonis Christofides Owned by: nobody
Component: Database layer (models, ORM) Version: dev
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

Steps to reproduce:

  1. Create these models:
    class Animal(models.Model):
        pass
    
    class Mammal(Animal):
        pass
    
    class Cat(Mammal):
        pass
    
  1. Query by pk, using a string instead of an integer:
    Animal.objects.get(pk="hello")
    Mammal.objects.get(pk="hello")
    Cat.objects.get(pk="hello")
    

Result: Querying Animal and Mammal raises a ValueError with the message "invalid literal for int() with base 10: 'hello'". This appears to be the desired behavior. However, querying Cat constructs an SQL query and attempts to run it, usually resulting in 'DataError: invalid input syntax for integer: "hello"'.

Expected result: In all cases the same exception should have been raised.

A practical problem caused by this is that if you give my app a wrong URL like /api/stations/hello/ (instead of e.g. /api/stations/25/), it results in an internal server error when it should have returned 404. The reason is that django-rest-framework catches ValueError but does not catch DataError.

I'm also attaching a file that you can merely run and it demonstrates the problem.

Attachments (1)

demo30627.py (1.7 KB ) - added by Antonis Christofides 5 years ago.
A single executable Python file that illustrates the problem

Download all attachments as: .zip

Change History (2)

by Antonis Christofides, 5 years ago

Attachment: demo30627.py added

A single executable Python file that illustrates the problem

comment:1 by Mariusz Felisiak, 5 years ago

Resolution: fixed
Status: newclosed
Summary: In multi-table inheritance, querying with invalid pk raises different exception depending on the inheritance levelIn multi-table inheritance, querying with invalid pk raises different exception depending on the inheritance level.
Triage Stage: UnreviewedAccepted
Version: 2.2master

Thanks for this report, it has been fixed as a side-effect in a4055adf702d086334a9ab2ca25a5e41e896a4fb. Fix will appear in Django 3.0 because it doesn't qualify for a backport.

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