'Replace UUID field content back to default null
Using Django==2.2.27, and Postgres
I have a Model, with a UUID field:
from django.db import models
class MyModel(models.Model):
uuid_field = models.UUIDField(
blank=True,
db_index=True,
null=True,
)
I need to delete the field (column) content for some objects (rows) - but when I try:
my_object.uuid_field = None
my_object.save()
I get this error:
ValidationError: ["'None' is not a valid UUID."]
^ That makes sense, since the value is definitely not a UUID: link
A bit more explanation:
- I can create objects without populating the
uuid_fieldso it stays null - I will most likely populate the
uuid_field - I might need to delete the
uuid_fieldcontent - I cannot change the
UUIDFieldto a char field or anything else
Is there a way to get the field back to its default null using Django ORM?
Thank you!
Solution 1:[1]
The non Django ORM solution I have is as such:
from django.db import connection
with connection.cursor() as cursor:
cursor.execute("UPDATE mymodelapp_mymodel SET uuid_field = null WHERE id = %s", [<MyModel id, int>])
I would love to get an ORM solution.
One thing I can do is to override models.UUIDField and customize it to behave as I would expect it to - but I am open to other ideas
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | camelBack |
