我需要的是允許用戶通過過濾其相關對象'小子」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)
所以與我的當前視圖功能如上所示。所有的孩子都必須在一個家長!
請幫忙!
哪裏有100個孩子的字典?示例中不存在 – 2ps
。我的意思是我想創建一個項目的列表/字典,我希望這些對象被 – DjangoGuy
篩選出來我想我真的不明白你的問題,因爲聽起來像你的問題,你已經「有一本字典有100孩子「。對不起。祝你好運! – 2ps