Can someone explain this simple, yet deceiving, anomaly?
There are two models, where B is a sub-model of A:
# models.py
class A(models.Model):
a = models.IntegerField(blank=True)
class B(A):
b = models.IntegerField(blank=True)
Simple, right? Yet in runtime:
>>> A()
<A: A object>
>>> B()
Traceback (most recent call last):
File "<console>", line 1, in <module>
File "django/db/models/base.py", line 357, in __init__
setattr(self, field.attname, val)
File "django/db/models/fields/related.py", line 271, in __set__
(instance._meta.object_name, self.related.get_accessor_name()))
ValueError: Cannot assign None: "B.b" does not allow null values.
What’s happening here? Why is A.a acting fine while B.b is unhappy about itself being blank?
Edit: I did notice that setting blank=True makes no difference on said behavior, but that still doesn’t explain this issue.
And now this: (?!?!?!)
>>> a = A(a=5)
>>> b = B(b=6)
Traceback (most recent call last):
File "<console>", line 1, in <module>
File "django/db/models/base.py", line 357, in __init__
setattr(self, field.attname, val)
File "django/db/models/fields/related.py", line 275, in __set__
self.related.get_accessor_name(), self.related.opts.object_name))
ValueError: Cannot assign "6": "B.b" must be a "B" instance.
OK, I managed to solve this mess.
The problem here is that the model and the field have the same name (case-agnostic). I had this both in my problematic model, as well as the examples here (
A.aandB.b).This is a Django problem in that the error is simply irrelevant to the real issue.
Bottom line – don’t have any field the same name as the model name.