Does rows exists in pivot table
Is there a cleaner way to check does all providers for item exists in pivot table? eg. I have few items, if one of them has all given providers then method should return True otherwise False
for item in items:
exists_count = 0
for provider in providers:
if ItemProviderConn.objects.filter(
item_id=item.pk,
provider_id=provider.pk,
):
exists_count += 1
else:
break
if exists_count == len(providers):
return True
return False
of Course you can do it better:
- I hope your
itemsandprovidersarequerySets. - if i right understand - you want to check, if all providers exists in any item.
in this case:
provider_ids = providers.values_list('pk', flat=True)
length_of_providers = len(provider_ids)
#1. get a filter for providers
queryset = items.filter(ItemProviderConn__provider_pk__in=provider_ids)
#2. count a providers_id's
queryset =queryset.annotate(providercount=Count('ItemProviderConn__provider_pk'))
#3. check if a count of providers_id => length_of_providers
queryset=queryset.filter(providercount__gte=length_of_providers)
#4. return True if any item has enough providers
return queryset.exists()
by the way - all work with item queryset i can do in line.