Skip to content

Commit

Permalink
Add examples of aliasing relationship to the cookbook
Browse files Browse the repository at this point in the history
  • Loading branch information
j4mie committed Jun 10, 2024
1 parent 2617735 commit 7f3c778
Showing 1 changed file with 46 additions and 0 deletions.
46 changes: 46 additions & 0 deletions docs/cookbook.md
Original file line number Diff line number Diff line change
Expand Up @@ -90,6 +90,52 @@ spec = [
]
```

## Alias a relationship

To alias a relationship, nest the relationship spec inside another dictionary:

```python
spec = [
"name",
{
"books_2022": {
"book_set": [
pairs.filter(publication_date__year=2022),
"id",
"title",
]
}
},
]
```

## Alias a relationship with a custom `to_attr`

The above example uses the default name (`book_set`) for the relationship when
the related objects are prefetched. If you wish to load the same relationship
multiple times with different filters, this won't work. To provide a `to_attr`
for the relationship, drop down to the `specs.relationship` function:

```python
from django_readers import specs


spec = [
"name",
{
"books_2022": specs.relationship(
"book_set",
[
pairs.filter(publication_date__year=2022),
"id",
"title",
],
to_attr="books_2022",
)
},
]
```

## Apply arbitrary queryset operations

```python
Expand Down

0 comments on commit 7f3c778

Please sign in to comment.