Django queryset to match all related objects

后端 未结 3 1203
暗喜
暗喜 2021-01-13 18:14

Let\'s say I have a ForeignKey from Coconut to Swallow (ie, a swallow has carried many coconuts, but each coconut has been carried by only one swallow). Now let\'s say that

3条回答
  •  暗喜
    暗喜 (楼主)
    2021-01-13 18:31

    See the docs on queries spanning multi-valued relationships -- you should chain filter calls.

    A simple way to go would be something like

    queryset = Swallow.objects.all()
    for coconut in coconuts:
        queryset = queryset.filter(coconuts_carried=coconut)
    

    A fancy way to do this in one line using reduce would be

    reduce(lambda q, c: q.filter(coconuts_carried=c), coconuts, Swallow.objects.all())
    

提交回复
热议问题