|
| 1 | +??? info "Our suggested ORM access method will be changed in a future update" |
| 2 | + |
| 3 | + The Django IDOM team is currently assessing the optimal way to integrate the [Django ORM](https://docs.djangoproject.com/en/dev/topics/db/queries/) with our React-style framework. |
| 4 | + |
| 5 | + This docs page exists to demonstrate how the ORM should be used with the current version of Django IDOM. |
| 6 | + |
| 7 | + Check out [idom-team/django-idom#79](https://github.com/idom-team/django-idom/issues/79) for more information. |
| 8 | + |
| 9 | +This is the suggested method of using the Django ORM with your components. |
| 10 | + |
| 11 | +```python title="components.py" |
| 12 | +from channels.db import database_sync_to_async |
| 13 | +from example_project.my_app.models import Category |
| 14 | +from idom import component, hooks, html |
| 15 | + |
| 16 | + |
| 17 | +@component |
| 18 | +def simple_list(): |
| 19 | + categories, set_categories = hooks.use_state(None) |
| 20 | + |
| 21 | + @hooks.use_effect |
| 22 | + @database_sync_to_async |
| 23 | + def get_categories(): |
| 24 | + if categories: |
| 25 | + return |
| 26 | + set_categories(list(Category.objects.all())) |
| 27 | + |
| 28 | + if not categories: |
| 29 | + return html.h2("Loading...") |
| 30 | + |
| 31 | + return html.ul( |
| 32 | + [html.li(category.name, key=category.name) for category in categories] |
| 33 | + ) |
| 34 | +``` |
| 35 | + |
| 36 | +??? question "Why does this example use `list()` within `set_categories`?" |
| 37 | + |
| 38 | + [Django's ORM is lazy](https://docs.djangoproject.com/en/dev/topics/db/queries/#querysets-are-lazy). Thus, `list()` is used to ensure that the database query is executed while within the hook. |
| 39 | + |
| 40 | + Failure to do this will result in `SynchronousOnlyOperation` when attempting to access your data. |
| 41 | + |
| 42 | +??? question "Why can't I make ORM calls without hooks?" |
| 43 | + |
| 44 | + Due to Django's ORM design, database queries must be deferred using hooks. Otherwise, you will see a `SynchronousOnlyOperation` exception. |
| 45 | + |
| 46 | + This may be resolved in a future version of Django with a natively asynchronous ORM. |
| 47 | + |
| 48 | +??? question "What is an ORM?" |
| 49 | + |
| 50 | + A Python **Object Relational Mapper** is an API for your code to access a database. |
| 51 | + |
| 52 | + See the [Django ORM documentation](https://docs.djangoproject.com/en/dev/topics/db/queries/) for more information. |
0 commit comments