Is There A Built-in Way to Filter with Given Function in Django?
<p>I especially wonder if I can use map, filter and reduce functions with Django model instances. If I cannot, is there a built-in way to pass a function to filter querying in Django?</p>

<p>Let me demonstrate my real problem for better understanding. I use PostgreSQL to use ArrayField and I have similiar model as below:</p>

<pre><code>class Route(models.Model):
    stops_forwards = ArrayField(
    ArrayField(
        models.PositiveIntegerField(),
        size=2
    ),
    default=[],
    verbose_name="Stops Forwards (Ordered)"
    )

    stops_backwards = ArrayField(
    ArrayField(
        models.PositiveIntegerField(),
        size=2
    ),
    default=[],
    verbose_name="Stops Backwards (Ordered)"
    )
</code></pre>

<p>As you can see above, I have embedded ArrayFields inside <code>stops_forwards</code> and <code>stops_backwards</code>. I use embedded ones  so as to keep it in order. An example data is shown as below:</p>

<pre><code>[
    [1, 35],
    [2, 40],
    [3, 180],
    [4, 285]
    # ... and it goes
]
</code></pre>

<p>What I want to do is to check if a particular stop id (like <code>285</code>) is in embedded ArrayField. Assuming that I have a function called <code>has_route_stop</code> that I do not know how it works but I call it as below:</p>

<pre><code>filter(lambda: has_route_stop(285), instances)
</code></pre>

<p>Or, is there a built-in way in Django API to do this?</p>

<hr>

<h1>Environment</h1>

<ul>
<li>Python 3.5.1</li>
<li>Django 1.9.9</li>
<li>PostgreSQL 9.5.4</li>
<li>psycopg2 2.6.2</li>
</ul>

<p>Django's Postgres integration allows you to query in embedded arrays using the <code>__contains</code> operator. So you can do:</p>

<pre><code>Route.objects.filter(stops_forwards__contains=[285])
</code></pre>

<p>See <a href="https://docs.djangoproject.com/en/1.10/ref/contrib/postgres/fields/#querying-arrayfield" rel="nofollow">the ArrayField documentation</a>.</p>

python django postgresql filter