Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

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

Closed
simkimsia opened this issue May 11, 2020 · 2 comments
Closed

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

simkimsia opened this issue May 11, 2020 · 2 comments

Comments

@simkimsia
Copy link

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

@coady
Copy link
Owner

coady commented May 13, 2020

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...

@simkimsia
Copy link
Author

Thanks!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants