0

I am using MySQL and Django in my backend, and the big issue now is that I use underscores in MySQL, while I have to use camelCase in Django ORM.So the question is, can I somehow tell Django to insert underscores in those places where it encounters uppercase letter in the middle of the word, so that

ownerAccount = models.ForeignKey(ownerAccount, models.CASCADE)

becomes owner_account_id in MySQL.

I know there is db_column solution, but it sounds like a hell to me and violation of DRY. I feel like there just should be a clean and quick solution for this

Edgar Navasardyan
  • 4,261
  • 8
  • 58
  • 121

1 Answers1

1

According to the naming conventions in PEP8, variable names should be written in lowercase, with words separated by underscores as necessary to improve readability.

Therefore your approach:

ownerAccount = models.ForeignKey(ownerAccount, models.CASCADE)

is wrong. And it is more than one issue:

1) the property name should be written as owner_account;

2) the class name should be written as OwnerAccount, thus models.ForeignKey(OwnerAccount), even better is to enclose the class name in quotes, like models.ForeignKey('OwnerAccount'), to make it more flexible;

3) for better readability and conforming to Django conventions you should use the keyword argument on_delete like on_delete=models.CASCADE.

The db_column has it's justification and without it the framework would be extremely unflexible and completely unusable in many cases.

To summarize, the quick and proper solution is to use snake_case for the property names of the model class (or any class).

EDIT:
If you create a REST API with Django REST Framework and want to have different names for the keys, like for example:

{'ownerAccount': 'some value'}

instead of:

{'owner_account': 'some_value'}

then you can change the output of the field names. There are two answers to this question which can help you further.

Once again I'd like to stress, regardless of the REST API, you should still conform to the PEP8 conventions and use snake_case for any class properties and methods.

cezar
  • 11,616
  • 6
  • 48
  • 84