注意:处理昂贵的企业遗留代码和不允许更改的模型
我想做的事:
- 将两个字段合并为一个DateTime字段
型号.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(),
)
)
...
所需结果:
2022-11-01 20:30:00+00:00
从团队中的其他人那里了解到
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="")