coady / django-model-values

Taking the O out of ORM.

Home Page:https://coady.github.io/django-model-values

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

What do you mean by classmethod? can you give an example?

simkimsia opened this issue · comments

You wrote here https://django-model-values.readthedocs.io/en/latest/example.html#table-logic

Table logic

Django recommends model methods for row-level functionality, and custom managers for table-level functionality. That’s fine if the custom managers are reused across models, but often they’re just custom filters, and specific to a model. As evidenced by django-model-utils’ QueryManager and PassThroughManager.

There’s a simpler way to achieve the same end: a model classmethod. In some cases a profileration of classmethods is an anti-pattern, but in this case functions won’t suffice. It’s Django that attached the Manager instance to a class.

Then you followed with an example of a classproperty.

I understand what you mean when you say custom managers are ok, if they are reused across models.

SO you're saying if there's a custom filter specific to a model, it's better off to write a classmethod.

This part I think I understand.

My question is what if it's a custom filter method specific to a model that creates new records?

Similar to get_or_create / update_or_create of the regular manager.

E.g.

from model_values import Manager as DataLayerManager

class Book(models.Model):
    data_layer = DataLayerManager # i prefer to use model_values as a separate manager keyword 

I like to have something like

Book.data_layer.create_draft(**various_parameters)

But of course the signature of create_draft is unique to Book. Do I use your classmethod suggestion?

Or alternatively, can you give an example of what you're trying to say specifically with regards to classmethod in this paragraph in the docs?

Thank you

An alternate constructor is probably the most common use of a classmethod, so I think it suits this case well. It just means the interface would be Book.create_draft instead of Book.data_layer.create_draft.

class Book(models.Model):
    data_layer = DataLayerManager()

    @classmethod
    def create_draft(cls, **...):
        cls.data_layer...

Thanks!