Legacy database odd primary key fields

1 view
Skip to first unread message

BenW

unread,
Nov 6, 2009, 3:16:41 PM11/6/09
to Django users
Hello,

I am trying to write models for a legacy database that defines it's
primary keys as (MySQL):

bigint unsigned not null default '0'

On the surface, this seems like a poor decision because the
application then has to manage PK uniqueness itself. My question is,
does anyone have any suggestions on how to define my models so that I
don't have to manage the uniqueness in MY application? I'm happy to
wrap whatever field I need to and do a SELECT MAX(id) ... + 1 behind
the scenes to get a unique PK.

My ultimate goal is to encapsulate all the legacy tables in my models
so I can use the model as if it had an AutoField.

Any suggestions are welcome!

Thanks,

ben

akaariai

unread,
Nov 6, 2009, 4:33:38 PM11/6/09
to Django users


On 6 marras, 22:16, BenW <benwil...@gmail.com> wrote:

> On the surface, this seems like a poor decision because the
> application then has to manage PK uniqueness itself.  My question is,
> does anyone have any suggestions on how to define my models so that I
> don't have to manage the uniqueness in MY application?  I'm happy to
> wrap whatever field I need to and do a SELECT MAX(id) ... + 1 behind
> the scenes to get a unique PK.

You can use a base model to inherit from for models that have such
primary keys. Write a save method something like this:

class Base:
id = models.IntegerField(primary_key=True)
class Meta:
abstract = True

def save:
if self.id set:
call super save()
else:
self.id = get a cursor, execute proper sql to get unique id
# Note that you probably want to inspect self._meta to be
able to
# create the correct sql automatically.
self.save(force_insert=True)

Using select max(id) + 1 is not safe, it can result in multiple
transactions getting the same id. You probably want to create a
sequence and get the id from the sequence.


BenW

unread,
Nov 6, 2009, 6:25:59 PM11/6/09
to Django users
That definitely looks like a good approach. By sequence, could I do
Model.objects.order_by('-id')[0].id + 1?

Also, what about using default= in the field constructor? I was
thinking about setting default to a PK generator that gets a unique
key

Thanks,

Ben
Reply all
Reply to author
Forward
0 new messages