Search code examples
pythondjangodjango-querysetdjango-filtermany-to-one

How to modify computed queryset values ? (Reversed many - to - one relationship)


class Style(Model):
    id ....
    name .... 

class Song(Model):
    ...
    style = ForgeignKey(Style, related_name="songs")

queryset = Style.objects.all()
queryset[0].songs = queryset[0].songs.filter(something=1)
#or
queryset[0].songs.set(queryset[0].songs.filter(something=1))

This is my actual code, but it does not work except for filtering... I would like to assigned queryset.songs new filtered songs...

or is there another way how to efficiently filter in this case ?


Solution

  • You can work with a Prefetch object [Django-doc]:

    from django.db.models import Prefetch
    
    queryset = Style.objects.prefetch_related(
        Prefetch('songs', Song.objects.filter(something=1))
    )

    If you access queryset[0].songs, you will only get the songs with something=1. This is of course the case for all Styles in the querset.