user2393267 user2393267 - 1 month ago 6
Python Question

django Field names must not end with an underscore. Field names must not contain __

I am new to django. While referring to django check framework documentation, I came across the following points :-


  • Field names must not end with an underscore.

  • Field names must not contain "__".



I am not able to know, why such restriction exists. Moreover, the django documentation is not clear about such restriction. I have googled about the same, but could not get any good answer for the same.

Thanks in advance.

Answer

This restrictions exist because django uses __ in filter lookups.

https://docs.djangoproject.com/en/1.10/topics/db/queries/#lookups-that-span-relationships

Django offers a powerful and intuitive way to “follow” relationships in lookups, taking care of the SQL JOINs for you automatically, behind the scenes. To span a relationship, just use the field name of related fields across models, separated by double underscores, until you get to the field you want.

So having it in field name will mess up lookup resolution

For trailing underscore is same reason. if you have it in field name separation will be messed up test___field.split('__') will become ['test', '_field'] not ['test_', 'field'].

Comments