Python Developer Guide
Other documentationsDemoCommunityGitHub
  • Forest Admin
  • Getting started
    • How it works
    • Quick start
      • Flask
      • Django
    • Create your agent
    • Troubleshooting
    • Migrating legacy agents
      • Pre-requisites
      • Recommendations
      • Migration steps
      • Code transformations
        • API Charts
        • Live Queries
        • Smart Charts
        • Route overrides
        • Smart Actions
        • Smart Fields
        • Smart Relationships
        • Smart Segments
  • Data Sources
    • Getting Started
      • Collection selection
      • Naming conflicts
      • Query interface and Native Queries
        • Fields and projections
        • Filters
        • Aggregations
    • Provided data sources
      • SQLAlchemy
      • Django
        • Polymorphic relationships
    • Write your own
      • Translation strategy
        • Structure declaration
        • Capabilities declaration
        • Read implementation
        • Write implementation
        • Intra-data source Relationships
      • Contribute
  • Agent customization
    • Getting Started
    • Actions
      • Scope and context
      • Result builder
      • Static Forms
      • Widgets in Forms
      • Dynamic Forms
      • Form layout customization
      • Related data invalidation
    • Charts
      • Value
      • Objective
      • Percentage
      • Distribution
      • Leaderboard
      • Time-based
    • Fields
      • Add fields
      • Move, rename and remove fields
      • Override binary field mode
      • Override writing behavior
      • Override filtering behavior
      • Override sorting behavior
      • Validation
    • Hooks
      • Collection hook
      • Collection override
    • Pagination
    • Plugins
      • Write your own
    • Relationships
      • To a single record
      • To multiple records
      • Computed foreign keys
      • Under the hood
    • Search
    • Segments
  • Frontend customization
    • Smart Charts
      • Create a table chart
      • Create a bar chart
      • Create a cohort chart
      • Create a density map
    • Smart Views
      • Create a Map view
      • Create a Calendar view
      • Create a Shipping view
      • Create a Gallery view
      • Create a custom tinder-like validation view
      • Create a custom moderation view
  • Deploying to production
    • Environments
      • Deploy on AWS
      • Deploy on Heroku
      • Deploy on GCP
      • Deploy on Ubuntu
    • Development workflow
    • Using branches
    • Deploying your changes
    • Forest Admin CLI commands
      • init
      • login
      • branch
      • switch
      • set-origin
      • push
      • environments:create
      • environments:reset
      • deploy
  • Under the hood
    • .forestadmin-schema.json
    • Data Model
      • Typing
      • Relationships
    • Security & Privacy
Powered by GitBook
On this page
  • Customization function
  • Enable support of live queries
  • Django and Async

Was this helpful?

  1. Data Sources
  2. Provided data sources

Django

PreviousSQLAlchemyNextPolymorphic relationships

Last updated 5 months ago

Was this helpful?

This is the official documentation of the forestadmin-agent-django and forestadmin-agent-flask Python agents.

The Django data source allows importing collections from all models of your Django project.

To make everything work as expected, you need to install the package django.

Note that:

  • Django relationships will be respected

  • The Django data source works with multiple databases

  • The Django data source is added by default when using Django agent. You can disable this behavior by adding FOREST_AUTO_ADD_DJANGO_DATASOURCE = False in your settings.py

Customization function

from forestadmin.datasource_django.datasource import DjangoDatasource
from forestadmin.django_agent.agent import DjangoAgent

def customize_forest(agent: DjangoAgent):
    #this is done automatically when FOREST_AUTO_ADD_DJANGO_DATASOURCE=True (default)
    agent.add_datasource(DjangoDatasource())
FOREST_CUSTOMIZE_FUNCTION = "my_app.forest_admin.customize_agent"
# or it can be a function directly
# from my_app.forest_admin import customize_agent
# FOREST_CUSTOMIZE_FUNCTION = my_app.forest_admin.customize_agent

# FOREST_AUTO_ADD_DJANGO_DATASOURCE = True

Enable support of live queries

By enabling this feature, users with the required permission level can create Live Query components (, and ), allowing them to create more sophisticated requests to your database, by leveraging the underlying query language, SQL in this case.

You can enable this feature by setting a connection name (works as an identifier) when creating your datasource. This connection name will be reflected on the UI when configuring a Live Query component, it should have a clear meaning for your Forest users.

agent.add_datasource(
    DjangoDatasource(live_query_connection="main_database"),
)

At this stage, ForestAdmin should display a connection field next to the live query input box.

Multi databases

To support multiple databases, the live_query_connection can support a mapping of {"connection_name": "database_name"}.

agent.add_datasource(
    DjangoDatasource(live_query_connection={
        "main_database":"default",
        "users_database":"users"
        }
    ),
)
DATABASES = {
    "default": {
        "NAME": "app_data",
        "ENGINE": "django.db.backends.postgresql",
        "USER": "postgres_user",
        "PASSWORD": "s3krit",
    },
    "users": {
        "NAME": "user_data",
        "ENGINE": "django.db.backends.mysql",
        "USER": "mysql_user",
        "PASSWORD": "priv4te",
    },
}

Django and Async

For custom functions such as actions, computed fields, hooks, etc..., if an asynchronous function is specified, it will be called in an asynchronous thread (also known as an event loop). Whereas if it's a synchronous function, it will be executed directly within a synchronous thread. The method call will be wrapped with sync_to_async.

Because the agent core operates asynchronously, some APIs are asynchronous. This can result in a combination of asynchronous calls to the Forest Admin API and synchronous calls to Django ORM from custom functions.

Asynchronous function

async def refund_order_execute(
    context: ActionContextSingle, result_builder: ResultBuilder
) -> ActionResult:
    id_ = await context.get_record_id()
    order = await Order.objects.aget(id=id_)
    # ...
    return result_builder.success(f"{order.amount}$ refunded.")

Or use sync_to_async:

from asgiref.sync import sync_to_async

async def refund_order_execute(
    context: ActionContextSingle, result_builder: ResultBuilder
) -> ActionResult:
    id_ = await context.get_record_id()
    order = await sync_to_async(Order.objects.get)(id=id_)
    # ...
    return result_builder.success(f"{order.amount}$ refunded.")

Synchronous function

In a synchronous context, you can query Forest Admin asynchronous methods with asyncio:

import asyncio

def refund_order_execute(
    context: ActionContextSingle, result_builder: ResultBuilder
) -> ActionResult:
    id_ = asyncio.run(context.get_record_id())
    order = Order.objects.get(id=id_)
    # ...
    return result_builder.success(f"{order.amount}$ refunded.")

Or use async_to_sync:

from asgiref.sync import async_to_sync

def refund_order_execute(
    context: ActionContextSingle, result_builder: ResultBuilder
) -> ActionResult:
    id_ = async_to_sync(context.get_record_id)()
    order = Order.objects.get(id=id_)
    # ...
    return result_builder.success(f"{order.amount}$ refunded.")

If you are working with and using the previous example, the connection main_database will be bind to the default database django is using.

The Forest Admin agent uses async internally, while . Under the hood, the agent uses sync_to_async to query the ORM.

In an asynchronous function, you can query the Django ORM with the :

charts ↗
analytics charts ↗
segments ↗
multiple databases ↗
Django ORM is part of Django async unsafe ↗
async methods provided by Django ↗