GithubHelp home page GithubHelp logo

Comments (4)

alfonsrv avatar alfonsrv commented on June 13, 2024 1

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.

matthewhegarty avatar matthewhegarty commented on June 13, 2024

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.

alfonsrv avatar alfonsrv commented on June 13, 2024

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.

matthewhegarty avatar matthewhegarty commented on June 13, 2024

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)

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo 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.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.