Remove autogenerated 'id' when using existing database

2,385 views
Skip to first unread message

Ben in campus

unread,
Apr 28, 2015, 8:05:02 AM4/28/15
to django-d...@googlegroups.com
Django Version: (1, 8, 0, 'final', 0)

Issue: I have an existing database, so I integrated it following the instruction in https://docs.djangoproject.com/en/1.8/howto/legacy-databases/ to inspectdb and generated models.py. That table does NOT have column 'id', so the generated models.py doesn't have 'id' either. The model is unmanaged (managed = False).
But the Django page failed, saying something like 'can not find id column in the table'. Somehow the query added 'id' in the select fields.


Fixed: Modified /usr/local/lib/python2.7/dist-packages/django/db/models/options.py
Old: line 284-287
            else:
                auto = AutoField(verbose_name='ID', primary_key=True,
                            auto_created=True)
                model.add_to_class('id', auto)
New:
            else:
                if self.managed:
                    auto = AutoField(verbose_name='ID', primary_key=True,
                            auto_created=True)
                    model.add_to_class('id', auto)

That works well for my system. I think it makes sense that Django should not add AutoField for unmanaged class.

Please confirm and decide whether to patch this into your code base. Thanks.



Javier Guerra Giraldez

unread,
Apr 28, 2015, 9:36:46 AM4/28/15
to django-d...@googlegroups.com
On Tue, Apr 28, 2015 at 1:59 AM, Ben in campus <benin...@gmail.com> wrote:
> That table does NOT have column 'id', so the generated models.py doesn't
> have 'id' either. The model is unmanaged (managed = False).


if your table has a primary key, add the primary_key=True flag to that
field and Django won't add an 'id' field.

--
Javier

Ben L

unread,
Apr 28, 2015, 11:35:45 AM4/28/15
to django-d...@googlegroups.com
It is true that the table doesn't have a primary key.

1, I might be able to talk to the DBA to add a primary key in here and re-sync the class. But is that required for each table to have pk to run Django?

2, what if I just modify the class to have fake pk =True, but not modify the database structure? Is that a common practice?

Thorsten Sanders

unread,
Apr 28, 2015, 11:45:26 AM4/28/15
to django-d...@googlegroups.com
I do that since years with tables not having a primary key without
problems, but I am only using django orm on those to select data.
Reply all
Reply to author
Forward
0 new messages