Django models in Many2Many relationship: filter by a group of member
<p>I have these models:</p>

<pre><code>class Skill(models.Model):
    name = models.CharField(max_length=20)


class Engineer(models.Model):
    name = models.CharField(max_length=20)
    skill = models.ManyToManyField(Skill)
    city = models.ForeignKey(City)


class City(models.Model):
    city = models.CharField(max_length=20)
</code></pre>

<p>I have 2 questions, please spare your time to help me. Thank you :)</p>

<p>1) I would like to filter Engineer by a group of skills. 
Let's say I need to filter engineers, who have these skills ['HTML', 'python', 'CSS']. How can I do that? </p>

<p>2) I would like to filter Engineer by a group of skills <strong>AND</strong> in a specific area. 
Let's say I need to filter engineers, who have these skills ['HTML', 'python', 'CSS'] <strong>AND</strong> this engineer must live in Anaheim. How can I do that? </p>

<p>You should read <em><a href="https://docs.djangoproject.com/en/1.10/topics/db/queries/#lookups-that-span-relationships" rel="nofollow">queries that span relationships</a></em> part of the docs. Basically querying is done in the same kinda syntax you do <em>ForeignKey</em> lookups. (In case you don't use <a href="https://docs.djangoproject.com/en/1.10/ref/models/fields/#django.db.models.ManyToManyField.through" rel="nofollow">m2m through</a> though)  </p>

<p>Also you don't have any relation between an <em>Engineer</em> and a <em>City</em>, If you want to be able to answer to queries like your second question, you need to add a <em>ForeignKey</em>, from <em>Engineer</em> to <em>City</em>.</p>

<p>1.</p>

<pre><code>skills = Skill.objects.filter(name__in=['HTML', 'Python', 'Css'])
engineers = Engineer.objects.filter(skill__in=skills)
</code></pre>

<p>2.</p>

<pre><code>city = City.objects.get(name='Anaheim')
engineers = Engineer.objects.filter(skill__in=skills, city=city) # Considering you put a ForeignKey from Engineer to City
</code></pre>

python django django-models