I've some classes like these :
class Event(models.Model):
beginning = models.fields.DateTimeField(null=False, blank=True, default=date.today)
end = models.fields.DateTimeField(null=False, blank=True, default=date.today)
class Festival(models.Model):
name = models.fields.CharField(max_length=100, blank=True)
def __str__(self) -> str:
return f"{self.name}"
class FestivalEdition(Event):
type = "festival_edition"
father_festival = models.ForeignKey(Festival, default="", on_delete=models.CASCADE, related_name="edition")
def __str__(self) -> str:
return f"{self.festival_name} {self.year}"
As you can see, only the children classes have their __str__ methods. When I use Event (by the admin interface or by shell), the name is like this <Event: Event object (1)>.
How can I use the __str__ methods of the children (and children of children) classes when calling the parent class ?
I've read the official documentation of Django about inheritance and this post.
I tried this :
class Event(models.Model):
objects2 = InheritanceManager()
# The __str__ of Event call the __str__ of children models
def __str__(self) -> str:
event_name = Event.objects2.filter(pk=self.pk).select_subclasses()[0].__str__()
return f"{event_name}"
It works well but only with the children but not the children of the children because I get this recursion Error in this case : RecursionError: maximum recursion depth exceeded while calling a Python object.
source https://stackoverflow.com/questions/75715719/use-str-children-classes-methods-when-calling-parent-class
Comments
Post a Comment