Django: __in query lookup doesn't maintain the order in queryset

后端 未结 4 1507
Happy的楠姐
Happy的楠姐 2020-12-23 21:11

I have ID\'s in a specific order

>>> album_ids = [24, 15, 25, 19, 11, 26, 27, 28]
>>> albums = Album.objects.filter( id__in=album_ids, publi         


        
相关标签:
4条回答
  • 2020-12-23 21:32

    You can't do it in django via ORM. But it's quite simple to implement by youself:

    album_ids = [24, 15, 25, 19, 11, 26, 27, 28]
    albums = Album.objects.filter(published=True).in_bulk(album_ids) # this gives us a dict by ID
    sorted_albums = [albums[id] for id in albums_ids if id in albums]
    
    0 讨论(0)
  • 2020-12-23 21:33

    You can do it in Django via ORM using the extra QuerySet modifier

    >>> album_ids = [24, 15, 25, 19, 11, 26, 27, 28]
    >>> albums = Album.objects.filter( id__in=album_ids, published= True
                 ).extra(select={'manual': 'FIELD(id,%s)' % ','.join(map(str, album_ids))},
                         order_by=['manual'])
    
    0 讨论(0)
  • 2020-12-23 21:43

    Assuming the list of IDs isn't too large, you could convert the QS to a list and sort it in Python:

    album_list = list(albums)
    album_list.sort(key=lambda album: album_ids.index(album.id))
    
    0 讨论(0)
  • 2020-12-23 21:54

    If you use MySQL and want to preserve the order by using a string column.

    words = ['I', 'am', 'a', 'human']
    ordering = 'FIELD(`word`, %s)' % ','.join(str('%s') for word in words)
    queryset = ModelObejectWord.objects.filter(word__in=tuple(words)).extra(
                                select={'ordering': ordering}, select_params=words, order_by=('ordering',))
    
    0 讨论(0)
提交回复
热议问题