Search code examples
pythondjangotypeerrorpython-docx

DateField to String formatting in QuerySEt


activitylist = sr.activity_set.all()
cell.paragraphs[0].text = activitylist.values_list('activityPlannedStartDate', flat = True)

I am getting an error of: 'in ' requires string as left operand, not datetime.date

cell.paragraphs[0].text is a cell in a predefined table in a docx that I build in Word.

Please help with this TypeError.

Thank you in advance!


Solution

  • You should use strftime method to format date to string. And use string.join to represent values list as a comma-separated string:

    formatted_dates = [date.strftime("%Y-%m-%d") for date in
                             activitylist.values_list('activityPlannedStartDate',
                                                      flat=True)]
    cell.paragraphs[0].text = ', '.join(formatted_dates)