Django queryset to match all related objects

后端 未结 3 1169
暗喜
暗喜 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:47

    I can have swallow.objects.filter(coconuts_carried__husk_sements__in = husk_segment_list) to show that this swallow has gripped at least one husk segment in the list.

    No, this is wrong, this gives you a list of swallows which have carried at least one husk segment from *husk_segment_list*.

    If I've understood right, we are talking about checking for a specific swallow.

    So, from your description I guess your models look something like this:

    class Swallow(models.Model):
        name = models.CharField(max_length=100)
    
    
    class Coconut(models.Model):
        swallow = models.ForeignKey(Swallow, related_name='coconuts_carried')
    
    
    
    class HuskSegment(models.Model):
        coconut = models.ForeignKey(Coconut, related_name='husk_segments')
    

    If you already have the husk segment list you need to check againts the swallows segments, there's no reason you need to resolve it in a query. Get the swallows' segments and check if it's a superset of your husk segment list.

    So we have:

    #husk_segment_list = [, , ...]
    husk_segments_set = set((husk.pk for husk in husk_segment_list))
    
    whitey = Swallow.object.get(name='Neochelidon tibialis')
    wh_segments_set = set((value[0] for value in HuskSegment.objects.filter(coconut__in=whitey.coconuts_carried.all()).values_list('id')))
    
    whitey_has_carried_all = wh_segments_set.issuperset(husk_segments_set)
    

提交回复
热议问题