Reputation: 7438
When saving to a django model via a dict which does have the key and value {...,'type': None,...}
the model field is
type = models.CharField(max_length=3, choices=Type.CHOICES, default=Type.EITHER)
However when trying to save I get an error: django.db.utils.IntegrityError: null value in column "type" violates not-null constraint
Does the ORM in django not try to use the default value if a None
is specified directly? How best should this be handled?
Update, more details on saving.
There is no custom save method in the model.
In the view this is being saved via
views.py
...
account = Account()
account_data = {}
...
preferences = ['type', 'payment_method_preference', ...]
account_fields = preferences + other_fields
for key in account_fields:
account_data[key] = request.session['supply_address'].get(key)
keys_to_attr(account_data, account)
account.address = address
account.payment = direct_debit
account.save()
Upvotes: 0
Views: 811
Reputation: 599530
This code is quite strange.
Your problem happens because you explicitly set every attribute, even if it is None, therefore overriding the default which was assigned on instantiation. You could check for this:
for key in account_fields:
value = request.session['supply_address'].get(key)
if value is not None:
account_data[key] = value
but really I would re-think what you are doing, I'm not sure why you want to copy a bunch of fields around instead of, for example, having Address as a separate model with a foreign key from Account.
Upvotes: 1