[Feature Request] Allow a Field/DeferredAttribute object everywhere a field name as a string is currently expected

41 views
Skip to first unread message

Matt del Valle

unread,
Jan 13, 2020, 11:09:39 AM1/13/20
to Django developers (Contributions to Django itself)
Hiya,

The title says it all. It would be dead useful if you could always use fields rather than the string name of a field, for example in a QuerySet order_by(), or in the BaseModelAdmin.ordering class attribute (and probably many more locations).

This has the huge advantage of avoiding string literals in your code, which allows static code analysis (MyPy, Pycharm's inspections, etc.) tools to warn you if you misspell the field name, or if you later rename the field. Otherwise such errors end up being hidden until that line of code happens to be actually run, which has the potential to slip through testing and end up in production. It also allows refactor/rename tools to automatically assist with renames in every such location across your Django project, saving a lot of time and effort.

It also seems really simple to implement. All you'd need would be a helper function that did a few if-elif checks for instances of Field or DeferredAttribute, and returned Field.name and DeferredAttribute.field.name respectively. It would return strings unchanged to preserve the current functionality.

The tricky part would be then tracking down everywhere within Django where such field name strings are expected and wrapping the input in this function.

Is there any chance something like this could be considered as a new feature?

Thanks in advance,
Matt

Tim Graham

unread,
Jan 13, 2020, 1:04:59 PM1/13/20
to Django developers (Contributions to Django itself)
If I understand correctly, currently this works:

Question.objects.order_by(Question.pub_date.field_name)

but your proposal is to avoid the need for ".field_name". I don't think I'd use that syntax as its more verbose and less readable (to me, anyway). Having more than one way to write things (string or field reference) isn't great for consistency. Strings would still be needed for referencing things like annotations.
Reply all
Reply to author
Forward
0 new messages