Comments (4)
Ah thinking SQL has increasingly become an up-hill battle once I started to delve into server-specific SQL-functions. Pair that with the Django query-specifics and I'm in awe by all the clever ways people come up with querying for things. I seriously don't know how people are doing it.
My favorite being queries like Model.objects.filter(last_datetime__lte=Now() + timedelta(seconds=1) * F("interval"))
Anyways, I solved this issue building on your answer by expanding the viewset's queryset as follows:
class ArtistViewSet():
...
def get_queryset(self):
queryset = super().get_queryset()
albums = Album.objects.filter(artist=OuterRef('pk')).order_by('-created')
queryset = queryset.annotate(
latest_album=Subquery(albums.values('name')[:1])
)
return queryset
Thanks.
from django-rest-framework-datatables.
You can get the latest album (by year) for each artist using a subquery (added in overridden get_queryset()
):
class AlbumViewSet(viewsets.ModelViewSet):
queryset = Album.objects.none()
serializer_class = AlbumSerializer
def get_queryset(self):
latest_album_qry = (Album.objects.filter(artist=OuterRef("artist_id")).order_by("-year"))[:1]
qs = Album.objects.all().order_by("pk")
qs = qs.filter(id__in=latest_album_qry.values("pk"))
return qs.prefetch_related("artist", "genres")
def get_options(self):
return get_album_options()
class Meta:
datatables_extra_json = ('get_options', )
This generates the following sql:
SELECT "albums_album"."id", "albums_album"."name", "albums_album"."rank", "albums_album"."year", "albums_album"."artist_id"
FROM "albums_album" INNER JOIN "albums_artist" ON ("albums_album"."artist_id" = "albums_artist"."id")
WHERE "albums_album"."id" IN (
SELECT U0."id" FROM "albums_album" U0 WHERE U0."artist_id" = "albums_album"."artist_id" ORDER BY U0."year" DESC LIMIT 1
)
ORDER BY "albums_artist"."name" ASC LIMIT 10;
from django-rest-framework-datatables.
Any way to get the Artist
as the primary queryset aka use an ArtistViewSet
? Say you'd want to display mainly the artist's information along with the latest Album
; this works, but messed up the hierarchy.
Another option would obviously be to de-normalize the Album
, saving it on the Artist
directly whenever a newer album is added via a signal
, but that is kind of less-than-ideal. To emulate that I added the property
, as it allows to keep the Artist
as the main model when querying and prevents logic duplication among multiple parts of the project / scattered querysets.
from django-rest-framework-datatables.
I'm not sure what you mean, but I would suggest you write the query you want as SQL SELECT
first, then port that over to a Django query. You might want to return all Artists, and then outer join the latest album onto each (query on Artist table); or you might just want the latest Album with associated Artist information (query on Album table).
from django-rest-framework-datatables.
Related Issues (20)
- Smart Filtering on the Server Side HOT 2
- "Illegal mix of collations for operation 'like'" utf8 search error HOT 3
- Travis build not running HOT 1
- DatatablesPageNumberPagination Ignores "PAGE_SIZE" default parameter in settings.py
- How to filter by date HOT 1
- DatatablesFilterBackend: performance gain by removing call to count() HOT 3
- Export all the results to the CSV HOT 1
- DatabaseError when using search HOT 1
- Issue retrieving fields with a 'source' attribute HOT 2
- Can't get filter method to work
- filter post with id
- can not disable paginintion for specific views HOT 2
- d.date and d.images return undefined in ?format=datatables but not with ?format=json HOT 1
- Sorting and pagintion and searching produces problemes
- Fail when using SQL query 'RawQuerySet' object has no attribute 'count' HOT 3
- deprecation warning due to no pyproject.toml
- Project dead? HOT 1
- Support for Datatables SearchBuilder?
- Default global and column search is not working in POST method
Recommend Projects
-
React
A declarative, efficient, and flexible JavaScript library for building user interfaces.
-
Vue.js
🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.
-
Typescript
TypeScript is a superset of JavaScript that compiles to clean JavaScript output.
-
TensorFlow
An Open Source Machine Learning Framework for Everyone
-
Django
The Web framework for perfectionists with deadlines.
-
Laravel
A PHP framework for web artisans
-
D3
Bring data to life with SVG, Canvas and HTML. 📊📈🎉
-
Recommend Topics
-
javascript
JavaScript (JS) is a lightweight interpreted programming language with first-class functions.
-
web
Some thing interesting about web. New door for the world.
-
server
A server is a program made to process requests and deliver data to clients.
-
Machine learning
Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.
-
Visualization
Some thing interesting about visualization, use data art
-
Game
Some thing interesting about game, make everyone happy.
Recommend Org
-
Facebook
We are working to build community through open source technology. NB: members must have two-factor auth.
-
Microsoft
Open source projects and samples from Microsoft.
-
Google
Google ❤️ Open Source for everyone.
-
Alibaba
Alibaba Open Source for everyone
-
D3
Data-Driven Documents codes.
-
Tencent
China tencent open source team.
from django-rest-framework-datatables.