0

I am writing a Django app which define groups of user. A user can be part of many groups.

I want to be able to retrieve, from a list of groups, users which are members of at least one of those groups and with no duplicate.

So i wrote a query to accomplish that. That method will take a list of group_id and simply returns a list of users. My question is: where is the best place to put that method?

I was thinking to create a custom manager for my Group model. But it don't seems logical as my method will return to me a list of Users.

According to the doc: https://docs.djangoproject.com/en/1.8/topics/db/managers/

Manager of a model should contains queries about that model.

After some research, I've seen that is not advised to extends the django.auth.models.User manager (at least in my case).

For the moment, i will just put my method in a 'service.py' file, but I was wondering if there is not a more elegant way to accomplish what i am trying to do.

Thanks by advance for your suggestions!

Jisson
  • 51
  • 7

2 Answers2

0

I assume there is a ManyToManyField relation from User to Group, like the following?

class Group(models.Model):
    users = models.ManyToManyField('auth.User')

I don't think there's a reason to write a method to achieve this, it's just a one-line call to filter:

User.objects.filter(groups__in=group_ids)

If you must make it a method, I don't think there's an "official" place to put this. The User manager would probably be closest, but as you say, adding a custom manager to User is a pain. Django apps are just python code, and aren't very prescriptive about where non-framework methods go, so put it where it makes sense for your code/team.

Note that Django already provides all of this functionality, and even names the model Group, so it seems like you're reinventing the wheel writing your own.

Lucas Wiman
  • 10,021
  • 2
  • 37
  • 41
  • Thanks for the answer. In fact, I already used User Groups for permission. My question was more about conception and where put that kind of code. My app is a newsletter and i wanted to be able to target very specific users with a newsletter campaign. But you're right, i totally can manage it with Django groups! :) – Jisson Sep 19 '16 at 23:38
0

In your views.py you can use the below function and call it in your view:

def get_groups_users(*groups):
    users = User.objects.filter(groups__name__in=list(groups))
    return list(set(users))
ettanany
  • 19,038
  • 9
  • 47
  • 63