I'm trying to create a rule to enforce the usage of related_name
when defining a ForeignKey field in Django, as well as its format.
Enforcing the usage of the field is done by the following rule:
- id: python.custom.foreign-key-must-set-related-name
message: ForeignKey relationships must explicitly set the `related_name` property as `<model>_<field>_set`
languages: [python]
severity: ERROR
patterns:
- pattern-inside: |
class $M(...):
...
- pattern-not: $F = django.db.models.ForeignKey(..., related_name=..., ...)
- pattern: $F = django.db.models.ForeignKey(...)
My goal now is to modify this rule to also be able to validate the format of the related_name, so that it is: <model>_<field>_set
(or, following the variables in the rule: $M_$F_set
)
I've been trying several combinations and haven't been lucky so far. Is this possible to do?
Edit:
As an example, look at the following model:
class MyCoolModel(models.Model):
correct_field = models.ForeignKey(to='something', related_name='mycoolmodel_correct_field_set')
incorrect_field = models.ForeignKey(to='something', related_name='something_set')