DjangoGuy DjangoGuy - 18 days ago 5
Python Question

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 in average.

if the kids in 1 parent object are all in the dictionary I want them to be listed.
But not all 100 kid have to be related to the parent object.

e.g if the parent have 4 kids who are in the dictionary and 1 that is not. Then do not include them.

I have the code below

models.py :

class Parent(models.Model):
title = models.CharField(max_length=250)
address = models.CharField(max_length=250)


class Kid(models.Model):
family = models.ForeignKey(Parent)
name = models.CharField(max_length=250)
age = models.IntegerField()
city = models.CharField(max_length=250)


Views.py :

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))
filter_ids = Kid.objects.filter(filter_q).values_list('family__id', flat=True).distinct()
exclude_ids = Kid.objects.exclude(filter_q).values_list('family__id', flat=True).distinct()
parents = Parent.objects.filter(id__in=filter_ids).exclude(id__in=exclude_ids)
template = 'index.html'
context = {'parents': parents}
return render(request, template, context)


so with my current view function shown above. all the kids have to be in 1 parent!!!

help please!

2ps 2ps
Answer

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)