#35866: Django documentaion style guide on models is unclear what to do with any
other Python dunder methods that the model class might have
--------------------------------------+------------------------------------
Reporter: Hristo Trendafilov | Owner: (none)
Type: Cleanup/optimization | Status: new
Component: Documentation | Version: dev
Severity: Normal | Resolution:
Keywords: | Triage Stage: Accepted
Has patch: 0 | Needs documentation: 0
Needs tests: 0 | Patch needs improvement: 0
Easy pickings: 0 | UI/UX: 0
--------------------------------------+------------------------------------
Comment (by Hristo Trendafilov):
Replying to [comment:2 Natalia Bidart]:
> Hello Hristo Trendafilov, thank you for taking the time to create this
report. To me, "any custom method" is a method that you "invent" for your
Model, not methods that are already "defined" by Python's base object
class.
>
> So my reading of that is that whatever extra business logic and helpers
that you need are after `get_absolute_url`. I agree we could make this
explicit in the docs though, accepting with that goal.
>
> Would you like to prepare a patch?
Hello, I have been thinking about that and my proposal is like so:
- All database fields
- Custom manager attributes
- class Meta
- any dunder and magic method(s), except `__str__()`
- `def __str__()`
- any `@property`/ies/ + setter/s/
- any `@classmethod`/s/
- any `@staticmethod`/s/
- `def save()`
- `def get_absolute_url()`
- Any other public methods
- Any other private methods
The reason for this is like so:
- Developers are keen on reusing methods as fast as possible, so important
things you might ever want to use or overwrite should be at the top, to
avoid scrolling.
- Properties might be considered as fields/Django Admin even allow you to
use those/, so those should be up but after the `__` methods and magic
methods to keep Python best practices for class ordering
- `__str__()` to be the last dunder, to conclude the dunder block, so that
you know that there will be no other `__` after that point. Also in rare
cases `__init__()` is used that might go to the top of the dunder block.
- Class methods and static methods should be at the top because they could
be widely used when a class is inherited or initialized and to avoid
scrolling.
- `def save()` and `def get_absolute_url() ` could be an anchor telling
you that from this point you might add your custom logic. It will be
easier to read because you will know that after this point there is some
custom logic.
- Finally, to avoid unnecessary scrolling, private methods should be at
the bottom, because most likely you will not need or want to look at
those.
If that is agreed upon, I am okay with fixing it.
--
Ticket URL: <
https://code.djangoproject.com/ticket/35866#comment:3>