rtindru
rtindru

Reputation: 5337

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.

Upvotes: 18

Views: 3396

Answers (2)

Antoine Pinsard
Antoine Pinsard

Reputation: 34922

It requires a little tweak, but I think you can do this by overriding the ForeignKey class:

from django.utils.text import camel_case_to_spaces


class MyForeignKey(models.ForeignKey):
    def contribute_to_class(self, cls, *args, **kwargs):
        super().contribute_to_class(cls, *args, **kwargs)

        if not cls._meta.abstract:
            related_name = self.remote_field.related_name
            related_query_name = self.remote_field.related_query_name
            underscore_name = camel_case_to_spaces(cls.__name__).replace(" ", "_")
            if related_name:
                self.remote_field.related_name = related_name.format(
                    underscore_name=underscore_name
                )
            if related_query_name:
                self.remote_field.related_query_name = related_query_name.format(
                    underscore_name=underscore_name
                )


class Animal(models.Model):
    class Meta:
        abstract = True

    habitat = MyForeignKey(
        Habitats, on_delete=models.CASCADE, related_name="{underscore_name}"
    )

Upvotes: 3

Antoine Pinsard
Antoine Pinsard

Reputation: 34922

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'

Upvotes: 16

Related Questions