- переопределяет
contribute_to_class()
из ForeignKey
, чтобы установить related_name .
class CustomFk(models.ForeignKey):
<b>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__))</b>
2. Используйте это пользовательское поле FK в абстрактной модели.
class Invoice(models.Model):
<b>user = CustomFk(User, related_name='%(class)s')</b>
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,
<b>related_name='Purchase_Invoice',</b> 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,
<b>related_name='Sale_Invoice',</b> to=settings.AUTH_USER_MODEL)),
],
options={
'abstract': False,
},
),
]
Ссылка
*. contribute_to_class()
*. Разделенная строка с заглавными буквами - Python