Szafran
Szafran

Reputation: 51

When should I create methods in model

I have model Post and i'm making querysets like this in view

user = CustomUser.objects.get(username=user)
blocked_users = user.blocked.all()
posts_except_blocked = Post.objects.exclude(author__in=blocked_users).order_by('-pub_date')

and a few similar. But i recognized that I can put this into model class as @staticmethod and now it's looking

@staticmethod
def get_posts_except_blocked(user):
    user = CustomUser.objects.get(username=user)
    blocked_users = user.blocked.all()
    return Post.objects.exclude(author__in=blocked_users).order_by('-pub_date')

Should I put every queries like this to model? I have there in views method

def create_notifications(post):
    for word in post.content_post.split():
        if '@' in word:
            user_to_notificate = CustomUser.objects.get(username=word[1:])
            TalkAbout(where=post, _from=post.author, to=user_to_notificate).save()

I'm calling it after save post form to create notifications. Can this be in views or maybe I need to put it in Post class too? Is it possible to call this function automaticly after creating post?

Upvotes: 0

Views: 550

Answers (1)

Muhammad Faizan Fareed
Muhammad Faizan Fareed

Reputation: 3748

Yes you can put class related methods into Model class. Or you can use Model Manager.

A Manager is the interface through which database query operations are provided to Django models. At least one Manager exists for every model in a Django application. The way Manager classes work is documented in Making queries; this document specifically touches on model options that customize Manager behavior.

Manager in Django offical doc

What is Manager in Djnago stackoverflow answer

Upvotes: 1

Related Questions