Opened 13 hours ago

Last modified 13 hours ago

#35866 new Cleanup/optimization

Django documentaion style guide on models is unclear what to do with any other Python dunder methods that the model class might have

Reported by: Hristo Trendafilov Owned by:
Component: Documentation Version: dev
Severity: Normal Keywords:
Cc: Micha Reiser Triage Stage: Accepted
Has patch: no Needs documentation: no
Needs tests: no Patch needs improvement: no
Easy pickings: no UI/UX: no

Description

Following the discussion here:
https://github.com/astral-sh/ruff/issues/13892#issuecomment-2436995567

It turns out that the Django documentation regarding model structuring https://docs.djangoproject.com/en/dev/internals/contributing/writing-code/coding-style/#model-style is unclear.

As proposed:

The order of model inner classes and standard methods should be as follows (noting that these are not all required):

    All database fields
    Custom manager attributes
    class Meta
    def __str__()
    def save()
    def get_absolute_url()
    Any custom methods

makes understanding that any other dunder, private methods and so on should come after the methods mentioned above,
which violates Python class best practices of structuring code in classes, where dunder methods should be on top, then constants, staticmethods, private methods and so on...

The following code is an example:

What Python best practices suggests:

class Person(models.Model):
    name = models.CharField(xxxx)    
    
    def __repr__(self):        
        return "something"

    def save(*args, **kwargs):
        super().save(*args, `**kwargs)

What Django documentation suggests:

class Person(models.Model):
    name = models.CharField(xxxx)
    
    # Django methods
    def save(*args, **kwargs):
        super().save(*args, `**kwargs)
    
    # Any custom methods
    def __repr__(self):        
        return "something"    

Change History (2)

comment:1 by Micha Reiser, 13 hours ago

Cc: Micha Reiser added

comment:2 by Natalia Bidart, 13 hours ago

Triage Stage: UnreviewedAccepted
Type: UncategorizedCleanup/optimization
Version: dev

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?

Note: See TracTickets for help on using tickets.
Back to Top