[Django]-How to customize related_name argument in Django

5๐Ÿ‘

โœ…

  1. override the contribute_to_class() of ForeignKey to set the related_name.
class CustomFk(models.ForeignKey):
    def contribute_to_class(self, cls, name, private_only=False, **kwargs):
        super().contribute_to_class(cls, name, private_only=False, **kwargs)
        self.remote_field.related_name = "_".join(re.findall('[A-Z][^A-Z]*', cls.__name__))

2. Use this custom FK field in abstract model.

class Invoice(models.Model):
    user = CustomFk(User, related_name='%(class)s')

    class Meta:
        abstract = True

# migrations file
operations = [
    migrations.CreateModel(
        name='PurchaseInvoice',
        fields=[
            ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
            ('field_purchase', models.CharField(max_length=255)),
            ('user', sample.models.CustomFk(on_delete=django.db.models.deletion.CASCADE,
                                            related_name='Purchase_Invoice', to=settings.AUTH_USER_MODEL)),
        ],
        options={
            'abstract': False,
        },
    ),
    migrations.CreateModel(
        name='SaleInvoice',
        fields=[
            ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
            ('field_sale', models.CharField(max_length=255)),
            ('user', sample.models.CustomFk(on_delete=django.db.models.deletion.CASCADE,
                                            related_name='Sale_Invoice', to=settings.AUTH_USER_MODEL)),
        ],
        options={
            'abstract': False,
        },
    ),
]

Reference
*. contribute_to_class()
*. Split string with uppercase letters- Python

๐Ÿ‘คJPG

Leave a comment