If I change the attribute of an abstract base class field like
Classname._meta.get_field(fieldname).attribute = 'value'
will it affect the other child classes fields too?
tl;dr - The change isn't magically reflected back to the previous usage of the abstract class.
Depends on where you make the attribute change. If you do it before the child class is defined, then the change will get reflected in that particular child class, but if you do it after the child class is defined, it wouldn't affect the child class' attribute.
class Foo(models.Model):
char = models.CharField(default='world!', max_length=32)
class Meta:
abstract = True
class Bar1(Foo):
pass
print('bar1 -', Bar1._meta.get_field('char').default)
Foo._meta.get_field('char').default = 'hello!'
print('changed to hello!')
class Bar2(Foo):
pass
print('bar1 -', Bar1._meta.get_field('char').default)
print('bar2 -', Bar2._meta.get_field('char').default)
Foo._meta.get_field('char').default = 'magic!'
print('changed to magic!')
class Bar3(Foo):
pass
print('bar1 -', Bar1._meta.get_field('char').default)
print('bar2 -', Bar2._meta.get_field('char').default)
print('bar3 -', Bar3._meta.get_field('char').default)
which gives the following output -
bar1 - world!
changed to hello!
bar1 - world!
bar2 - hello!
changed to magic!
bar1 - world!
bar2 - hello!
bar3 - magic!
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.