I have on several occasions needed to annotate a boolean. The way that I
have found to do this is to use a conditional expression, but it seems
awfully noisy to my eyes. It seems like it might be better to allow
directly annotating Q objects, or perhaps providing a simple wrapper to
convert a Q object into a boolean field expression.
For example, instead of this:
{{{#!python
notes = notes.filter(user=self.user).annotate(
is_author=Case(
When(author_id=self.request.user.id, then=True),
default=Value(False),
output_field=BooleanField(),
),
)
}}}
I think that there's a good case to be made that this should be possible:
{{{#!python
notes = notes.filter(user=self.user).annotate(
is_author=Q(author_id=self.request.user.id),
)
}}}
Or if we really can't have the `Q` object doing double duty, we could wrap
that Q object in some expression constructor. I didn't provide an example,
because I couldn't think of a great and obvious name for such a
constructor.
--
Ticket URL: <https://code.djangoproject.com/ticket/30061>
Django <https://code.djangoproject.com/>
The Web framework for perfectionists with deadlines.
* type: Uncategorized => New feature
* version: 2.1 => master
* component: Uncategorized => Database layer (models, ORM)
* stage: Unreviewed => Accepted
Comment:
It currently works and is tested with an `ExpressionWrapper` (see #26517)
but allowing direct usages of `Q` would definitely be simpler.
--
Ticket URL: <https://code.djangoproject.com/ticket/30061#comment:1>
Comment (by Ryan Hiebert):
Thank you for letting me know that, Simon. That's such a useful feature,
that even if using {{{Q}}} objects directly is rejected for some reason
(though I hope not), it would be very useful to document that it is
possible to use {{{Q}}} objects in an {{{ExpressionWrapper}}}.
For anyone that might come across this issue looking for this feature, the
syntax that currently works and is tested is like this:
{{{#!python
notes = notes.filter(user=self.user).annotate(
is_author=ExpressionWrapper(
Q(author_id=self.request.user.id),
output_field=BooleanField(),
),
)
}}}
--
Ticket URL: <https://code.djangoproject.com/ticket/30061#comment:2>
* status: new => closed
* resolution: => duplicate
Comment:
Duplicate of #27021.
--
Ticket URL: <https://code.djangoproject.com/ticket/30061#comment:3>