I have a Django model, DocumentComments
, with two datetime fields, created
and updated
. I am working on a search function that parses a search string and returns a Q expression to query the DocumentComments
model based on the values in the search string.
I need to write something like Q(created.year=xxxx)
, where created.year
is the year in the created
datetime field. But "keywords can't be expressions" as Django has been telling me all morning.
I tried using a custom model manager and annotating the default queryset with a year field, but that did not work as I can't seem to access the created.year
value in the get_queryset
function.
class DocumentCommentManager(models.Manager):
def get_queryset(self):
c_year = self.created.year
u_year = self.updated.year
return super(DocumentCommentManager, self).get_queryset().annotate(created_year=c_year, updated_year=u_year)
What am I missing, or what is a better way to accomplish my goal?
Thanks!
Mark
question from:
https://stackoverflow.com/questions/65908505/how-to-add-a-calculated-field-to-a-django-query-expression 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…