I'm trying create a model inherit following this tutorial: https://www.digitalocean.com/community/tutorials/understanding-class-inheritance-in-python-3
Everything works. Can access FirstName property in child and show in view but when I run makemigration/migrate
,inheriteds fields aren't created in table in database. (core-shark / core-trout)
What am I doing wrong? Is possible, using python inherits and CBV, to create fields in database by makemigration/migrate?
model.py
class Fish(models.Model):
def __init__(self, first_name, last_name="Fish"):
self.first_name = first_name
self.last_name = last_name
def swim(self):
print("The fish is swimming.")
def swim_backwards(self):
print("The fish can swim backwards.")
class Meta:
verbose_name = 'Fish'
abstract = True
def __str__(self):
return self.first_name
class Shark(Fish):
def __init__(self, first_name, last_name="Shark", skeleton="cartilage", eyelids=True):
self.first_name = first_name
self.last_name = last_name
self.skeleton = skeleton
self.eyelids = eyelids
def swim_backwards(self):
print("The shark cannot swim backwards, but can sink backwards.")
class Trout(Fish):
def __init__(self, water ='', price = 0):
self.water = water
self.price = price
super().__init__(self)
class Meta:
verbose_name = 'Trout'
view.py
class IndexView(TemplateView):
template_name = 'index.html'
def get_context_data(self, **kwargs):
context = super(IndexView, self).get_context_data(**kwargs)
sammy = Shark("Sammy")
terry = Trout()
terry.first_name = "Terry"
context['sammy'] = sammy
context['terry'] = terry
return context
index.html
...
<body style="color:red">
<h1>Fish Name: {{sammy.first_name}}</h1>
<h1>Fish Name: {{terry.first_name}}</h1>
</body>
...
[2
According to the Django Documentation for Models, you need to define your database fields as Class attributes.
I.o.w:
class Fish (models.Model):
first_name = models.CharField(max_length=64)
last_name = models.CharField(max_length=64)
def __init__(self, first_name, last_name="Fish"):
self.first_name = first_name
self.last_name = last_name
Doing so will allow them to be created in the database when you run the migration.