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.