How to set a default value for an inherited field in Django with multi-page inheritance?

I am using Django 1.6 and have code similar to this:

class Message (models.Model):
   message_type = models.CharField(max_length=1)

class MessageA (Message):
    some_field_for_a = models.CharField(max_length=1)

class MessageB (Message):
    some_field_for_b = models.CharField(max_length=1)

I want to save a new message to the database like this:

message_a = MessageA()
message_a.save()

But with the current implementation, I need to explicitly declare message_typeas follows:

message_a = MessageA()
message_a.message_type = "A"
message_a.save()

This is clearly inaccurate because it MessageAhas a default message_type = "A". Is there any way Django can escape this template code and set it message_typeautomatically for each inherited class (bearing in mind that hiding the field is not allowed and overriding should be avoided __init__)?

+4
source share

Source: https://habr.com/ru/post/1540599/


All Articles