2016-11-17 8 views
0

私は、ユーザーがParentの詳細を他のモデルのためにフォームに投稿できるフォームを用意しています。私は必要なもの関連するオブジェクトに基づくオブジェクトをフィルタする

は、その関連するオブジェクトをフィルタリングすることによりKid

Parentオブジェクトのリストにアクセスするには、ユーザーがのがXY都市に住んでZよりも古いという名前の子を持つとNOを持っている親オブジェクトの一覧を表示するフィルターを言わせできるようにすることです子供のXは、Zよりも若く、Yに住んでいます。

models.py

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


class Kid(models.Model): 
    cities = (
     ('city1', city1), 
     ('city2', city2) 
    ) 
    family = models.ForeignKey(Parent) 
    title = models.CharField(max_length=250) 
    age = models.CharField(max_length=250) 
    city = models.CharField(choices=cities) 

Views.py:views.py iはタプルとしてパターンを列挙されたが、うまくいきませんでした示したよう

def index(request): 
    my_pattern = (
    (name=samy, age_lt=15, city=paris), 
    ) 
    filter_ids = Kid.objects.filter(my_pattern).values_list('parents_id', flat=True).distinct() 
    exclude_ids = Kid.objects.exclude(my_pattern).values_list('parents_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) 

これは、最初にQを追加する以外のdjango Qオブジェクトを行う方法であるかどうかも疑問に思っています。

答えて

0

my_patternは辞書であり、フィルターでアンパックして除外する必要があります。除外するには**を使用する必要があります。

def index(request): 
    my_pattern = {'name': 'samy', 'age__lt': 15, 'city': 'paris'} 
    filter_ids = Kid.objects.filter(**my_pattern).values_list('family_id', flat=True).distinct() 
    exclude_ids = Kid.objects.exclude(**my_pattern).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) 

あなたがみとめパターンを持っている場合は、あなたが、私はこのエラーを得たQオブジェクト

import operator 
from functools import reduce 

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

を使用する必要があります。フィールドにキーワード「age_lt」を解決できません。選択肢は次のとおりです:年齢、都市、家族、家族ID、氏名、名前 また、「パターン」アイテムが含まれているかどうかは疑問です。何が除外されるのですか? – DjangoGuy

+0

@DjangoGuy検索に二重アンダースコア '__'を含める必要があります。これは' age__lt'のように –

+0

のエラーが修正されています。今はこのエラーがあります 'parents_id'というキーワードをフィールドに解決できません。選択肢は次のとおりです:年齢、都市、家族、家族ID、氏名、名前 – DjangoGuy

関連する問題