# Segments

{% hint style="success" %}
This is the official documentation of the `forestadmin-agent-django` and `forestadmin-agent-flask` Python agents.
{% endhint %}

A Segment is a subset of a Collection: it's a saved filter of your Collection.

Segments are designed for those who want to *systematically* visualize data according to specific sets of filters. It allows you to save filter configurations so user don’t have to do repetitive actions every day.

![](https://2921382565-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2F2HgnlEINLUAEQC1KgN48%2Fuploads%2Fgit-blob-b91265b079fd224c5918e2e8fabdee9d1f92d6c4%2Fsegment-example.png?alt=media)

## From your admin panel

Segments can be configured from the interface, without the need to write any code.

This is documented in the [User Guide](https://docs.forestadmin.com/user-guide/collections/segments).

## From your Agent

Sometimes, Segment filters are complicated and closely tied to your business. Forest Admin allows you to code how the Segment is computed.

For instance, in our [Live Demo example](https://app.forestadmin.com/livedemo), we’ve implemented a Segment on the collection `products` to allow admin users to see the bestsellers at a glance.

### Example

The only requirement when implementing a Segment from your agent is to return a valid `ConditionTree`.

```python
from forestadmin.datasource_toolkit.context.collection_context import CollectionCustomizationContext
from forestadmin.datasource_toolkit.interfaces.query.aggregation import Aggregation
from forestadmin.datasource_toolkit.interfaces.query.condition_tree.nodes.leaf import ConditionTreeLeaf

async def most_purchased_segment(context: CollectionCustomizationContext):
    # Query the ids of the 10 most populate products
    # by looking at the `orders` collection.
    rows = await context.datasource.get_collection("order").aggregate(
        context.caller,
        Aggregation({"operation": "Count", "groups": [{"field": "product_id"}]}),
        10,
    )

    # Return a condition tree which matches those records
    return ConditionTreeLeaf("id", "in", [row["product_id"] for row in rows])

agent.customize_collection("products").add_segment(
    "mostPurchased", most_purchased_segment
)
```
