On Wed, Aug 19, 2015 at 3:18 PM, Nikunj Badjatya
<
nikunjb...@gmail.com> wrote:
> Hello All,
>
> I have a django model class defined as:
>
>
> class Test(models.Model):
> id=AutoField(primary_key=True)
> name = models.CharField(max_length=45, null=False)
> description = models.CharField(max_length=200, null=True)
> uuid = models.CharField(max_length=250)
> class Meta:
> managed = False
> db_table ="test"
>
> Where,
> uuid is auto generated using a mysql trigger.
>
> Mysql Trigger looks like:
> DROP TRIGGER IF EXISTS `test_uuid`//
> CREATE TRIGGER `test_uuid` BEFORE INSERT ON` test
> `
> FOR EACH ROW begin if (new.uuid is null or new.uuid = '') then set new.uuid
> = (select uuid());end if; end
> //
> This trigger is added at the db level.
>
> i.e., any new insert in 'test' table would generate the value for uuid
> column.
> and insert works fine for this model from the code.
Why do you want to do this way?
>
> Issue is, when I try to access the uuid after I have performed the save(), I
> am getting null.
>
> row = Test(name=in_data['name'],
> description=in_data['description'],
> )
> row.save() # This creates a row with id, name, description and uuid (auto
> generated by the pre insert rigger)
> print(
row.id) # Prints id
> print(row.uuid) # Prints u' '
>
>
>
>
> Any idea as to what may be going on?
> Why row.uuid is coming as empty from the code though the uuid is clearly
> generated in the db table.
>
When you save something to the database, Django does not re-select out
the data that you just saved, and the contents of a model instance are
exactly as they were before you saved it - as far as django is
concerned, it has just persisted the most up to date version of it
*from* that model instance, so it would be wasteful to re-select it
out.
This is because django is an ORM, it knows about its own data
serialization, but nothing about your DB level trigger modifying the
data that it serializes.
You have two straightforward options - move the uuid setting code to a
django pre-save hook (ideally using the built in UUID field), or every
time you save an object, remember to re-fetch it from the database.
Whatever you do, presumably you are using UUIDs as an opaque
identifier, and will query the database by UUID to find an object, and
so the UUID field should be declared as db_index=True.
Cheers
Tom
PS:
UUIDs are 128bit integers - 16 bytes. Storing a 128 bit integer as a
variable length string of up to 250 bytes is going to be massively
inefficient, so you really should use a UUID type (new in 1.8) so that
it uses the best type it can for your database backend, either native
uuid or a fixed 32 char string.