2

I've got a model with a UUID primary key:

    id = models.UUIDField(
        primary_key = True,
        default = uuid.uuid4,
        editable = False,
        null = False,
        blank = False,
        help_text = 'The unique identifier of the Node.'
    )

The issue I'm trying to solve is that Django always seems to try an Update before an Insert.

The Django Docs seem to be explicit on what the behavior should be: If pk is None then it will try an INSERT first, otherwise an UPDATE.

When I create a ModelInstance, it autopopulates id with a UUID, so it's not none. Is there a way I can make it not do this?

Regardless, even if I set id and pk to None on create, it still does an UPDATE first:

my_totally_new_node = Node(data = data, id = None, pk = None)
my_totally_new_node.id
> None
my_totally_new_node.pk
> None
reset_queries()

my_totally_new_node.save()

connection.queries
> [{'sql': 'UPDATE "connection_p...::uuid", 'time': '0.002'}, {'sql': 'INSERT INTO "connect...::bytea)", 'time': '0.001'}]

To summarize:

  1. Is there a way I can cause default behavior for the ID field to be not to populate on create, but to still populate on Save?
  2. Any ideas why Django isn't following the documented behavior when pk is None and is still trying an INSERT first?

I'm aware of the save(force_insert=True) workaround but I'm looking for a better way, partly because create doesn't support this workaround.

Caleb Mac
  • 83
  • 5
  • 1
    It is being automatically filled in because you have: `default = uuid.uuid4`. To not have it do that remove the `default`. Then you will need some sort of mechanism on the server side to generate the `UUID`. – Adrian Klaver Sep 04 '20 at 15:59
  • @AdrianKlaver Thanks for your answer. Just to clarify, by server side you mean on the database server? – Caleb Mac Sep 04 '20 at 18:39
  • Yes. Postgres has a [UUID](https://www.postgresql.org/docs/current/uuid-ossp.html) extension. I have not done it, but I could see using that to set a default on the table column in Postgres. – Adrian Klaver Sep 04 '20 at 19:27

0 Answers0