开发者

django: how do i stop save(using=) from creating new primary key

In django, I want to copy data from identical tables in one db to those in another -- from 'db01' to 'default'. Schema are identical.

>>> a=Household.objects.filter(h_identifier='H122000-48').usi开发者_开发问答ng('db01')
>>> a[0].pk
>>> u'451465ea-0137-11e0-879a-70f1a16e0f80'
>>> a[0].save(using='default')
>>> b=Household.objects.filter(h_identifier='H122000-48').using('default')
>>> b[0].pk
>>> u'7c2484fe-8641-11e0-b080-00188b4d6b0e'

it works but the primary key for the record inserted into 'default' is not the same as the one fetched from 'db01'. To maintain integrity with other tables, the pk must not change. The django docs section selecting-a-database-for-save suggests that since instance 'a' already has a primary, the same primary key will be used when a new record is inserted to 'default'. I cannot get it to do that.

Does anyone know if this can be done? thanks in advance!!

(This may seem like an odd setup, but the application runs independently on disconnected netbooks during the day, and data is merged into a master db during the night when all the netbooks are docked. I can do it fine in mysql but would like to use the django ORM if possible.)


I know this is from a while ago, but I had the same issue today - judging by the key you're using, your id field is of type UUIDField from django_extensions?

It's slightly buggy, as the pre_save signal will always ensure the key is replaced regardless of whether there's one already existing. Subclassing it and replacing the pre_save function fixes it.

class FixedUUIDField(UUIDField):
def pre_save(self, model_instance, add):
    value = super(UUIDField, self).pre_save(model_instance, add)
    if self.auto and add and not value:
        value = unicode(self.create_uuid())
        setattr(model_instance, self.attname, value)
    return value


The django docs suggest using 'force_insert':

The second option is to use the force_insert option to save() to ensure that Django does a SQL INSERT:

p = Person(name='Fred') p.save(using='first') p.save(using='second', force_insert=True) This will ensure that the person named Fred will have the same primary key on both databases. If that primary key is already in use when you try to save onto the second database, an error will be raised.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜