Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Django Abstract Models setting related_name with underscores

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.

like image 791
rtindru Avatar asked Jul 24 '15 09:07

rtindru


1 Answers

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'
like image 105
Antoine Pinsard Avatar answered Oct 13 '22 15:10

Antoine Pinsard