简体   繁体   中英

How to customize related_name argument in Django

I have an abstract model and two child models such as:

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

    class Meta:
        abstract=True

class SaleInvoice(Invoice):
    field_sale = models.CharField(max_length=255)

class PurchaseInvoice(Invoice):
    field_purchase = models.CharField(max_length=255)

Now the reverse name for the child models would be saleinvoices and purchaseinvoices . But what I need is sale_invoices and purchase_invoices . How to achieve this? An underscore in between CamelCase.

  1. override the contribute_to_class() of ForeignKey to set the related_name .
class CustomFk(models.ForeignKey):
    


2. Use this custom FK field in abstract model.

class Invoice(models.Model):
    

    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,
                                             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,
                                             to=settings.AUTH_USER_MODEL)),
        ],
        options={
            'abstract': False,
        },
    ),
]

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM