Home How to Handle in Django - Exception Type: MultipleObjectsReturned
Reply: 1

How to Handle in Django - Exception Type: MultipleObjectsReturned

Prashant
1#
Prashant Published in 2017-09-13 11:48:06Z

Here I am struggling with the handling the exception, here is the details of my data models.

Routes Model-

class Routes(models.Model):
    serial_no = models.IntegerField(primary_key=True)
    toll = models.CharField(max_length=1000, blank=True, null=True)
    cost = models.CharField(max_length=300, blank=True, null=True)
    t = models.ForeignKey('Tollmaster', models.DO_NOTHING, blank=True, null=True)
    r = models.ForeignKey(Routeinfo, models.DO_NOTHING)

    class Meta:
        managed = True
        db_table = 'routes'
        unique_together = (('serial_no', 'r'),) 

But in admin panel I am getting error

MultipleObjectsReturned at /admin/tollm/routes/27/change/
get() returned more than one Routes -- it returned 2!
Request Method: GET
Request URL:    http://127.0.0.1:8000/admin/tollm/routes/27/change/
Django Version: 1.11.5
Exception Type: MultipleObjectsReturned
Exception Value:    
get() returned more than one Routes -- it returned 2!
Exception Location: C:\Users\prash\AppData\Local\Programs\Python\Python36-32\lib\site-packages\django\db\models\query.py in get, line 384
Python Executable:  C:\Users\prash\AppData\Local\Programs\Python\Python36-32\python.exe
Python Version: 3.6.2

I am using Postgresql database, here is the schema for this table,

              Table "public.routes"
  Column   |          Type           | Modifiers
-----------+-------------------------+-----------
 serial_no | integer                 | not null
 toll      | character varying(1000) |
 cost      | character varying(300)  |
 t_id      | integer                 |
 r_id      | character varying(300)  | not null
Indexes:
    "sno_rid_pkey" PRIMARY KEY, btree (serial_no, r_id)
Foreign-key constraints:
    "r_rinfo_fk" FOREIGN KEY (r_id) REFERENCES routeinfo(r_id)
    "t_id_fk" FOREIGN KEY (t_id) REFERENCES tollmaster1(tid)

any help would be appreciated.

Iain Shelvington
2#
Iain Shelvington Reply to 2017-09-13 14:01:48Z

Your model does not match the table schema. The table schema has a multi-column primary key on serial_no and r_id whereas your model specifies serial_no as a single column primary key.

Django does not support multi-column primary keys see here for the details

I would suggest changing your schema to add a separate auto-incrementing primary key column "id" and change your current primary key to a unique constraint

You need to login account before you can post.

About| Privacy statement| Terms of Service| Advertising| Contact us| Help| Sitemap|
Processed in 0.304539 second(s) , Gzip On .

© 2016 Powered by cudou.com design MATCHINFO