Django/PostgreSQL custom TimeRangeField



我试图创建一个TimeRangeField,但在保存到数据库(PostgreSQL 9.5.23版本(时遇到了一些问题。

from psycopg2.extras import DateTimeRange
from django import forms
from django.contrib.postgres.forms import BaseRangeField
from django.contrib.postgres.fields.ranges import RangeField
from django.db import models

class TimeRangeFormField(BaseRangeField):
default_error_messages = {'invalid': 'Enter two valid times.'}
base_field = forms.TimeField
range_type = DateTimeRange

class TimeRangeField(RangeField):
base_field = models.TimeField
range_type = DateTimeRange
form_field = TimeRangeFormField
def db_type(self, connection):
return 'tsrange'

保存时的错误似乎很容易解释——我很确定我需要将时间对象强制转换为字符串,但我不知道如何做到这一点。

function tsrange(time without time zone, time without time zone, unknown) does not exist
LINE 1: ...('b9925dd3-d4a8-4914-8e85-7380d9a33de5'::uuid, 1, tsrange('1...
^
HINT:  No function matches the given name and argument types. You might need to add explicit type casts.

这是SQL:

INSERT INTO "fulfillment_deliveryslot"
(
"uuid",
"day_id",
"window",
"max_orders",
"is_active"
)
VALUES
(
'b9925dd3-d4a8-4914-8e85-7380d9a33de5'::uuid,
1,
tsrange('12:38:31'::time, '13:00:00'::time, '[)'),
5,
true
)
returning "fulfillment_deliveryslot"."id" 

问题就在这里:time without time zone。您正在使用tsrange,这需要一个时间戳:

https://www.postgresql.org/docs/9.5/rangetypes.html

tsrange—不带时区的时间戳范围

换句话说,您正在将时间传递给需要时间戳的东西。

最新更新