简体   繁体   中英

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?

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM