# Django Integration

## Setup

```bash
pip install yoro[django]
```

### settings.py

```python
INSTALLED_APPS = [
    # ...
    "django.contrib.gis",       # GeoDjango required
    "yoro.django",
]
```

### urls.py

```python
from django.urls import include, path

urlpatterns = [
    path("api/v1/yoro/", include("yoro.django.urls")),
]
```

### Migrate

```bash
python manage.py migrate
```

This creates the `GeoAltiusCode` table with PostGIS geometry columns.

## Model: GeoAltiusCode

The `GeoAltiusCode` model stores encoded coordinates with their Hilbert cell geometry:

| Field | Type | Description |
|-------|------|-------------|
| `code` | `CharField(20)` | Yoro code (unique, indexed) |
| `domain` | `CharField(5)` | ISO domain prefix |
| `location` | `PointField` | GPS center point (SRID 4326) |
| `cell` | `PolygonField` | Hilbert cell bounding polygon |
| `precision` | `SmallIntegerField` | Hilbert order |
| `resolution_m` | `FloatField` | Cell size in meters |
| `label` | `CharField(255)` | Optional human label |
| `created_at` | `DateTimeField` | Auto-set on creation |

## Services

### get_or_create_altius_code

```python
from yoro.django.services import get_or_create_altius_code

obj = get_or_create_altius_code(lat=5.345, lon=-4.028, domain="CI")
print(obj.code)       # "CI-PV9XD"
print(obj.cell)       # Polygon geometry
```

### assign_altius_code

Assigns a Yoro code to any model instance that has `location` (PointField) and `altius_code` (ForeignKey) fields. Modifies the instance in place but does **not** save.

```python
from yoro.django.services import assign_altius_code

# In your model's save() method:
class MyLocation(models.Model):
    location = gis_models.PointField(srid=4326)
    altius_code = models.ForeignKey(
        "yoro.GeoAltiusCode",
        null=True, blank=True,
        on_delete=models.SET_NULL,
    )

    def save(self, **kwargs):
        if self.location and not self.altius_code_id:
            assign_altius_code(self, domain="CI")
        super().save(**kwargs)
```

## API Endpoints

| Method | URL | Description |
|--------|-----|-------------|
| GET | `/encode/?lat=6.8&lon=-5.3&domain=CI` | Encode GPS to code |
| GET | `/decode/?code=CI-PV9XD` | Decode code to GPS |
| GET | `/precisions/?domain=CI` | List canonical precisions |
| GET | `/domains/` | List all domains |

## Admin

`GeoAltiusCode` is automatically registered with the GIS admin, showing the map widget for `location` and `cell` fields.
