overwrite field value in subclasses

29 views
Skip to first unread message

Emmanuel Jannetti

unread,
Nov 23, 2012, 10:40:50 AM11/23/12
to django...@googlegroups.com
Hi all,

One piece of my model is as follow :

class UpperAbstract(models.Model):
  CHOICE_A = 0
  CHOICE_B = 1
  CHOICE_C = 2
  myfield = models.PositiveSmallIntegerField(choices=((CHOICE_A,'A'),(CHOICE_B,"B"),(CHOICE_C,"C")),blank=False)
  class Meta:
abstract = True

class Foo(UpperAbstract):
      myfield = UpperAbstract.CHOICE_A



I am expecting any instance of Foo being created, to have 'myfield' always and "automatically" set to UpperAbstract.CHOICE_A
In my test the created object as null value and saving it is refused on IntegrityError because 'myfield' cannot be None

thank in advance for any help.
regards

manu





Peter of the Norse

unread,
Nov 25, 2012, 8:14:15 PM11/25/12
to django...@googlegroups.com
Foo.myfield is 0, but when you created a new models.Field object in the abstract class, it did some deep magic. There’s also Foo._meta.fields which has the old myfield in it. The only thing you can do is create a new myfield with default=0 and editable=False.
Peter of the Norse
Rahm...@Radio1190.org



Emmanuel Jannetti

unread,
Nov 26, 2012, 4:19:18 AM11/26/12
to django...@googlegroups.com
Hi,

Thank for the reply.

Digging into _meta.fields of a created instance I see, as you said that myfield is still defined as in the upper class.

If I understood correctly your answer sub-class should have the field "redefine" instead of assigned .
something like 
myfield = models.PositiveSmallIntegerField(editable=False,default=UpperAbstract.CHOICE_A)

doing this , model validation raise a fieldRerror exception arguing that I am not allowed to do that because a field with the same
name already exists.

Did I misunderstood your comment ?

thx
manu





Emmanuel Jannetti

unread,
Nov 26, 2012, 4:30:54 AM11/26/12
to django...@googlegroups.com
Hi,
checking on my side.
All this works as soon as upper class are not abstract.

regards 
manu
Reply all
Reply to author
Forward
0 new messages