pythondjangodatetimedjango-modelsdjango-annotate

How to cast django.db.models F to a String?


Note: working on expensive corporate legacy code and models that are not allowed to be changed

What I'm trying to do:


Model.py:

from django.db import models

class DateThing(models.Model):
    date = models.DateField()
    start_time = models.CharField("Start time", max_length=255)

Viewset.py

from datetime import datetime
from django.db.models import F
from django.db.models.functions import Concat
from rest_framework import mixins, viewsets

class ViewSet(viewsets.GenericViewSet, mixins.ListModelMixin):
    date_things = DateThing.objects.annotate(
        start=Concat(
            F("date"),
            Value(" "),
            datetime.strftime(
                datetime.strptime(str(F("start_time")), "%I:%M %p"),
                "%H:%M",
            ),
            Value("+00:00"),
            output_field=CharField(),
        )
    )

    ...

Desired result:

2022-11-01 20:30:00+00:00

Solution

  • Figured it out from someone else on the team

    class ViewSet(viewsets.GenericViewSet, mixins.ListModelMixin):
        queryset_shifts = DateThing.objects.annotate(
            s_time=Cast("start_time", output_field=TimeField()),
            start=Concat(
                F("date"),
                Value(" "),
                F("s_time"),
                Value("+00:00"),
                output_field=CharField(),
            ),
        ).exclude(start_time="")