我有一个抽象模型和两个子模型,例如:
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)
现在,子模型的反向名称将为saleinvoices
和purchaseinvoices
。但是我需要的是sale_invoices
和purchase_invoices
。如何实现呢? CamelCase之间的下划线。
答案 0 :(得分:2)
contribute_to_class()
中的 ForeignKey
,以设置 related_name 。< / li>
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.在抽象模型中使用此 自定义FK字段 。
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,
},
),
]
参考
*。 contribute_to_class()
*。 Split string with uppercase letters- Python