The original title of this issue was "Annotate of _count in query optimizer not working as described in docs (attribute error)" and I've left the issue and my own response to it here. Digging through it, the actual issue is the way in which root queries need to be declared in multi-app setups (ie most setups) in django.
I think the real solution to this is for the getting started
to contain improved representation of the realistic case where you want your root Query
defined in schema.py and import queries from one or more apps. The django example could also adopt a more representative structure. Otherwise it's just incredibly hard to grow out of the 'getting stated' stage.
It wouldn't hurt to have a structuring your application
section of the docs either
In the query optimizer docs there is an example where we can get the count of a related FK field by annotating the queryset:
#models.py
class Artist(models.Model):
name = models.CharField()
class Album(models.Model):
name = models.CharField()
release_date = models.DateTimeField()
artist = models.ForeignKey("Artist", related_name="albums")
#types.py
from strawberry import auto
import strawberry_django
@strawberry_django.type(Artist)
class ArtistType:
name: auto
albums: list["AlbumType"]
albums_count: int = strawberry_django.field(annotate=Count("albums"))
But if I make a query like the following:
query ExampleQuery($artistId: Int!) {
artist(id: $artistId) {
albumsCount
}
}
I get the following response:
{
"data": null,
"errors": [
{
"message": "'Artist' object has no attribute 'albums_count'",
"locations": [
{
"line": 6,
"column": 5
}
],
"path": [
"artist",
"albumsCount"
]
}
]
}
Pay now to fund the work behind this issue.
Get updates on progress being made.
Maintainer is rewarded once the issue is completed.
You're funding impactful open source efforts
You want to contribute to this effort
You want to get funding like this too