2016-11-19 14 views
0

我需要的是允許用戶通過過濾其相關對象'小子」Filter對象是否所有foreignkeys在字典中

我們有有100孩子的字典訪問Parent對象列表。和平均約有5個孩子的父母。
如果1個父對象中的孩子都在字典中,我希望他們被列出。 但並非所有的100個孩子都必須與父對象相關。

例如,如果父母有4個孩子在字典中,1個不是。那麼不要包含它們。

我具有低於

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) 

所以與我的當前視圖功能如上所示。所有的孩子都必須在一個家長!

請幫忙!

+0

哪裏有100個孩子的字典?示例中不存在 – 2ps

+0

。我的意思是我想創建一個項目的列表/字典,我希望這些對象被 – DjangoGuy

+0

篩選出來我想我真的不明白你的問題,因爲聽起來像你的問題,你已經「有一本字典有100孩子「。對不起。祝你好運! – 2ps

回答

0

這是我會做的,如果我正確理解你的問題。

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)  
+0

只是爲了詳細說明。如果字段「名稱」是名稱模型的前綴鍵,該怎麼辦? – DjangoGuy

+0

是的,但我們需要看到'Name'模型定義,以確保我們在正確的過濾器上匹配。但實質上,你可以將'patterns'中的'name'改爲'name__field_to_match'(例如''name__first_name'') – 2ps

+0

class Name(models.Model): title = models.CharField(max_length = 250) – DjangoGuy

相關問題