'Q' object has no attribute 'split' - Django
Asked Answered
P

1

9

I have a Model:

class Authors(models.Model):
   name = models.TextField()
   person = models.ForeignKey(Person)

and query:

authors = Author.objects.filter(
                                (Q(name__iregex=r"\y{0}\y".format(s1)),
                                ~Q(name__iregex=r"\y{0}\y".format(s2))
                                ),
                                person=None).order_by('-id')

I am getting the error:

'Q' object has no attribute 'split'

why is this? i am not using split() though.. the line of error is in this query line.

Penzance answered 3/4, 2014 at 17:29 Comment(2)
What does \y match? I've never seen it before.Swap
@Swap matches only whole words and not part of words.. https://mcmap.net/q/802571/-whole-word-match-only-in-django-queryPenzance
V
10

I think you need to join your Q() filters with a logical operator like | or &.

authors = Author.objects.filter(
                                (Q(name__iregex=r"\y{0}\y".format(s1)) &
                                ~Q(name__iregex=r"\y{0}\y".format(s2))
                                ),
                                person=None).order_by('-id')
Vagarious answered 3/4, 2014 at 17:37 Comment(5)
i thought, , stays for &, doesnot it?Penzance
I think because you have the Q() objects wrapped in a paren, you need to use & explicitly. I.e, you have filter( (Q(), Q()), person=None). Does changing to & work? I'm not entirely confident about this answer TBH hahaVagarious
@Furbeenator docs.djangoproject.com/en/1.7/topics/db/queries/…Vagarious
Thanks, @Sohan Jain. I see they state Q objects can be combined using the & and | operators. When an operator is used on two Q objects, it yields a new Q object. but the examples didn't show any &s and they are implied with the filter. It would be nice if the docs showed when the explicit & is required, rather than have to lookup the "split" error. Thanks again, this got me out of a jam!Petal
Actually I still don't see clearly when we have to use the explicit and/or notation and when comma separated Q are enough...Heidy

© 2022 - 2024 — McMap. All rights reserved.