django-postgres-extra
django-postgres-extra copied to clipboard
Enable insert_and_get to work even when not using on_conflict
I have an insert query where I would like to have the database generate some field using a sequence. At the moment, Django does not return the generated field from the database by default, so I would like to use insert_and_get
to add an additional (or all) fields to the RETURNING
clause of my insert statement.
I don't need any special on_conflict
behavior, I would just like to return the database generated field and have Django properly update the model field instead of only returning the pk.
It appears that the insert_and_get
method is not exposed by PostgresManager
. Is there any reason I must use on_conflict
to get the entire row returned?
To clarify, I would simply like to execute
INSERT INTO my_table (some_field, another_field) VALUES (something, something_else) RETURNING *;
and have the Django model be updated appropriately.
The reason it isn't exposed on the manager is because without a conflict target, it'll just default to Django's create_and_get
: https://github.com/SectorLabs/django-postgres-extra/blob/master/psqlextra/query.py#L214
Your use case is not something I originally envisioned.
However, I don't see why we couldn't support your use case as well. You'd have to extend the SQL compiler because it assumes that there's a conflict target: https://github.com/SectorLabs/django-postgres-extra/blob/master/psqlextra/compiler.py
@Photonios not sure if it will help with implementation at all, but I was able to work around with vanilla Django by adding a db_returning = True
class property to the field classes where I have DB generated values.
It looks like base Django has already implemented most of what is required for arbitrary RETURNING
clauses, except they haven't made it public API for some reason.