mirror of
https://github.com/simonw/datasette.git
synced 2025-12-10 16:51:24 +01:00
?_labels= and ?_label=COL to expand foreign keys in JSON/CSV
These new querystring arguments can be used to request expanded foreign keys
in both JSON and CSV formats.
?_labels=on turns on expansions for ALL foreign key columns
?_label=COLUMN1&_label=COLUMN2 can be used to pick specific columns to expand
e.g. `Street_Tree_List.json?_label=qSpecies&_label=qLegalStatus`
{
"rowid": 233,
"TreeID": 121240,
"qLegalStatus": {
"value" 2,
"label": "Private"
}
"qSpecies": {
"value": 16,
"label": "Sycamore"
}
"qAddress": "91 Commonwealth Ave",
...
}
The labels option also works for the HTML and CSV views.
HTML defaults to `?_labels=on`, so if you pass `?_labels=off` you can disable
foreign key expansion entirely - or you can use `?_label=COLUMN` to request
just specific columns.
If you expand labels on CSV you get additional columns in the output:
`/Street_Tree_List.csv?_label=qLegalStatus`
rowid,TreeID,qLegalStatus,qLegalStatus_label...
1,141565,1,Permitted Site...
2,232565,2,Undocumented...
I also refactored the existing foreign key expansion code.
Closes #233. Refs #266.
This commit is contained in:
parent
0c22fa8f09
commit
ed631e690b
9 changed files with 276 additions and 69 deletions
|
|
@ -1,4 +1,5 @@
|
|||
from contextlib import contextmanager
|
||||
from collections import OrderedDict
|
||||
import base64
|
||||
import hashlib
|
||||
import imp
|
||||
|
|
@ -802,6 +803,23 @@ def path_with_format(request, format, extra_qs=None):
|
|||
return path
|
||||
|
||||
|
||||
class CustomRow(OrderedDict):
|
||||
# Loose imitation of sqlite3.Row which offers
|
||||
# both index-based AND key-based lookups
|
||||
def __init__(self, columns):
|
||||
self.columns = columns
|
||||
|
||||
def __getitem__(self, key):
|
||||
if isinstance(key, int):
|
||||
return super().__getitem__(self.columns[key])
|
||||
else:
|
||||
return super().__getitem__(key)
|
||||
|
||||
def __iter__(self):
|
||||
for column in self.columns:
|
||||
yield self[column]
|
||||
|
||||
|
||||
def value_as_boolean(value):
|
||||
if value.lower() not in ('on', 'off', 'true', 'false', '1', '0'):
|
||||
raise ValueAsBooleanError
|
||||
|
|
|
|||
Loading…
Add table
Add a link
Reference in a new issue