Chaining Q objects

34 visninger
Gå til det første ulæste opslag

MikeKJ

ulæst,
19. sep. 2018, 10.29.2019.09.2018
til Django users
Using this as an example from Dan Herrar
enter code here

        from django.db.models import Q
        user_pk = 1
        category_pk = 1  #some times None
        f = Q( user__pk = user_pk, date=now() )
        if category_pk is not None:
            f &= Q( category__pk = category_pk )
        todays_items = Item.objects.filter( f  )

I am constructing a massive filter chain (I'd rather not) so I have...
enter code here

        from django.db.models import Q
        f = Q(availability_text=this)
        if 'cabins' in request.POST:
            cabins = request.POST['cabins']
            if cabins != "0" and cabins != "":
                c = cabins
                c = int(c)
                f &= Q(cabins=c)
            if 'thruster' in request.POST:
                thruster = request.POST['thruster']
                if thruster != 0:
                    t = 1
                    f &= Q(thruster=t)

etc etc

this is the result of an f trial

(AND: ('availability_text', ''), ('bow_thruster', 1))

but I get

"Too many values to unpack" at

                wm = Boat.objects.filter(name=x).filter( f )[:1].get()

which is confusing as I am handling 4 lists and this is the 3rd iteration and it didn't error on iteration 1 or 2

Any insight would be gratefully received

Matthew Pava

ulæst,
19. sep. 2018, 10.36.1319.09.2018
til django...@googlegroups.com

I’m not entirely sure if the error is from your Q chain, but something I would try is to replace “[:1].get()” with “.first()”.

wm = Boat.objects.filter(name=x).filter( f ).first()

--
You received this message because you are subscribed to the Google Groups "Django users" group.
To unsubscribe from this group and stop receiving emails from it, send an email to django-users...@googlegroups.com.
To post to this group, send email to django...@googlegroups.com.
Visit this group at https://groups.google.com/group/django-users.
To view this discussion on the web visit https://groups.google.com/d/msgid/django-users/80b8d218-f948-4985-a825-f5d13af1f4ca%40googlegroups.com.
For more options, visit https://groups.google.com/d/optout.

Simon Charette

ulæst,
19. sep. 2018, 10.45.0719.09.2018
til Django users
Hey Mike,

Please provide the full traceback.

Also, since all your conditions are ANDed you could use a dict to build filter() kwargs instead of Q() objects.

Cheers,
Simon

To post to this group, send email to djang...@googlegroups.com.

MikeKJ

ulæst,
24. sep. 2018, 12.13.0424.09.2018
til Django users
Cheers Matthew, can't use .first() due to reskinning an existing site with an older version

To post to this group, send email to djang...@googlegroups.com.

MikeKJ

ulæst,
24. sep. 2018, 12.13.4624.09.2018
til Django users
many thanks Simon dict filter kwargs was definitely the way to go!
Svar alle
Svar til forfatter
Videresend
0 nye opslag