Skip to content Skip to sidebar Skip to footer

Filter Objects If All Its Foreignkeys Are In A Dictionary

what i need is to allow users to access list of Parent objects by filtering their related objects `Kid' We have a dictionary that has a 100 kid. and parents that have about 5 kids

Solution 1:

Here is what I would do if I understood your question correctly.

def index(request):
    patterns = [
        {'name': 'samy', 'age__lt': 15, 'city': 'paris'},
        {'name': 'sally', 'age__gt': 20, 'city': 'london'}
    ]
    filter_q = reduce(operator.or_, map(lambda p: Q(**p), patterns))      
    qs = Kid.objects.filter(filter_q).values_list('id', 'family_id') 
    family_ids = set()
    child_ids = list()
    for child_id, family_id in qs:
        family_ids.add(family_id)
        child_ids.append(child_id)        
    # At this point we have the complete list of matching Kid(s) in child_ids
    # . . . and we have a list of all family IDs in which those Kid(s) exist
    # Now we look for incomplete families, 
    # i.e., families that were part of the first query, 
    # but have Kid(s) that are not in our complete list 
    # of matching kids.
    incomplete_family_ids = set(Kid.objects.exclude(id__in=child_ids).filter(family_id__in=family_ids).values_list('family_id', flat=True).distinct())
    # Now we find the set complement to make life on the database a little easier.
    complete_family_ids = family_ids - incomplete_family_ids
    parents = Parent.objects.filter(id__in=complete_family_ids)
    template = 'index.html'
    context = {'parents': parents}
    return render(request, template, context)    

Post a Comment for "Filter Objects If All Its Foreignkeys Are In A Dictionary"