Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add examples of aliasing relationships to the cookbook #102

Merged
merged 2 commits into from
Jun 10, 2024
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
44 changes: 44 additions & 0 deletions docs/cookbook.md
Original file line number Diff line number Diff line change
Expand Up @@ -90,6 +90,50 @@ 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",
specs.relationship(
"book_set",
[
pairs.filter(publication_date__year=2022),
"id",
"title",
],
to_attr="books_2022",
)
]
```

## Apply arbitrary queryset operations

```python
Expand Down
Loading