Django: Where should I put queries about User which is in relation with other models
<p>I am writing a Django app which define groups of user. A user can be part of many groups.</p>

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

<p>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?</p>

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

<p>According to the doc: <a href="https://docs.djangoproject.com/en/1.8/topics/db/managers/" rel="nofollow">https://docs.djangoproject.com/en/1.8/topics/db/managers/</a></p>

<p>Manager of a model should contains queries about that model.</p>

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

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

<p>Thanks by advance for your suggestions!</p>

<p>I assume there is a <code>ManyToManyField</code> relation from <code>User</code> to <code>Group</code>, like the following?</p>

<pre><code>class Group(models.Model):
    users = models.ManyToManyField('auth.User')
</code></pre>

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

<pre><code>User.objects.filter(groups__in=group_ids)
</code></pre>

<p>If you must make it a method, I don't think there's an "official" place to put this. The <code>User</code> manager would probably be closest, but as you say, adding a custom manager to <code>User</code> 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.</p>

<p>Note that <a href="https://docs.djangoproject.com/en/1.10/topics/auth/default/#permissions-and-authorization" rel="nofollow">Django already provides all of this functionality</a>, and even names the model <code>Group</code>, so it seems like you're reinventing the wheel writing your own.</p>

python django django-models django-orm django-managers