I am relatively new to Django, but trying to learn quickly.
So, let’s say I want to make a new field, color, required on an existing Car model. The model already exists with data in the db, but the color field is new. That being said, I would like the user to have to decide a color for the car when they go through the webapp page and not be able to avoid it.
It seems simple enough to throw “blank=False, null=False” in the model definition and to call it a day, until you go to migrate your model changes.
You ask yourself “what do you populate all of the existing rows with?” You don’t pick a color, because you don’t want to make all of the existing cars red. I thought about just making it an empty string during the one-off migration process, but I wasn’t sure if there would be unintended problems associated with that later.
So then I thought to provide a default of “unspecified”, that way the db will be filled with that for existing cars and it’s not blank, so cool.
I thought I could validate that the user didn’t leave it as “unspecified” when they go to update it, so I tried to validate in the serializer. Then I tested it… and realized patch requests would also use this default, so if a user made an update via patch request, they could just avoid mentioning the field and it would stay unspecified. Darn.
So then I thought to validate at the viewset level, but then realized our application actually relies on patch requests and this would break those, as it would always require you to include ALL required fields for the model, even if the fields were on a different section or page than the one you were making changes to in the app.
My leading idea is to just do blank=True, null=True without specifying a default, make the migration. Then update the DB with all of the “unspecified” values directly. Then change the model to blank=False, null=False and the DB is fine and now the field will be required to be mentioned as expected and there won’t be a default to be slotted in on patch requests at the serializer level, but I still am not sure that the serializer level validation would catch an omission of the ‘color’ field…
I feel like a crazy person. This is not that crazy of a thing, but I have no clue what the best way forward is design-wise.
Please help me to learn? Thank you!