I have two Django model classes with their respective DB tables, both using the same class method. So I refactored and created an abstract parent class with the class method:
from django.db import models
from django.forms.models import model_to_dict
class Parent(models.Model):
@classmethod
def get_random(cls, variables: Set[str]) -> str:
elements: list = []
for o in cls.objects.filter(active=True):
elements.append(model_to_dict(o, fields=["id", "string"]))
chosen: dict = choice(elements)
# some other code...
return chosen["string"]
class Child1(Parent):
string = models.CharField(max_length=100)
type = models.ManyToManyField(Type, related_name="article_titles")
active = models.BooleanField(default=True)
class Meta:
db_table = "table_child_1"
class Child2(Parent):
string = models.TextField()
active = models.BooleanField(default=True)
class Meta:
db_table = "table_child_2"
When I call the method on one of the child class with chosen_string: str = Child1.get_random(variables=variables)
for example, I get a Django DB error:
django.db.utils.OperationalError: no such table: app_name_parent
.
So it seems the parent class method is called on the default Django DB table name for parent class, instead of the child.
What do I miss here? What would be the most elegant solution for using the same custom class method requesting the DB for two Django models?