I have an Abstract base model and 2 inheriting models, and I need to force the related_name to be in a specific format.
class Animal(models.Model):
legs = models.IntegerField(related_name='%(class)s')
habitat = models.ForeignKey(Habitats, related_name='%(class)s')
class DogAnimal(BaseModel):
name = models.CharField(max_length=20, related_name='dog_animal')
class CatAnimal(BaseModel):
name = models.CharField(max_length=20, related_name='cat_animal')
Generally, related_name = '%(class)s' will result in catanimal and doganimal respectively.
I need underscored values like this: dog_animal, cat_animal
Here is the 'Why' I need to do this - Legacy. These models were not organized with a base class - so the related_name originally specified was 'dog_animal' and 'cat_animal'. Changing this would be a lot of work.
A solution might be not to specify the related_name
for habitat
and define a default_related_name
for all children:
class Animal(models.Model):
class Meta:
abstract = True
habitat = models.ForeignKey(Habitats, on_delete=models.CASCADE)
class DogAnimal(Animal):
class Meta:
default_related_name = 'dog_animal'
class CatAnimal(Animal):
class Meta:
default_related_name = 'cat_animal'
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With