1

我有一个非常简单的模型:

from django.contrib.postgres.fields import IntegerRangeField
from django.db import models


class Production(models.Model):
    title = models.CharField(max_length=100, blank=True, db_index=True)
    year = models.PositiveSmallIntegerField(blank=True, default=0, db_index=True)
    index = models.PositiveSmallIntegerField(blank=True, default=0)
    run_years = IntegerRangeField(blank=True, null=True)

    class Meta:
        unique_together = ('title', 'year', 'index')

但是,当我通过update_or_create方法操纵我的模型时,我遇到了一种非常奇怪的行为。出于某种原因,我的IntegerRange领域刚刚被抹去。

In [1]: Production.objects.update_or_create(**{'title': '#twentyfiveish', 'year': 2017, 
        'index': 0, 'run_years': (2017, 2017)})[0].run_years
Out[1]: (2017, 2017)

In [2]: Production.objects.update_or_create(**{'title': '#twentyfiveish', 'year': 2017, 
        'index': 0, 'run_years': (2017, 2017)})[0].run_years
Out[2]: NumericRange(empty=True)

这对我来说不是一种理想的行为。这是一个错误吗?请指教。

版本:

  • 姜戈 1.11
  • PostgreSQL 9.6.3
4

1 回答 1

1

不幸的是,这是“设计的”。放在一起

无论保存数据时指定的范围如何,PostgreSQL 总是以规范形式返回一个范围,其中包括下限并排除上限;那是 [)。

-- includes no points (and will be normalized to 'empty')
SELECT '[4,4)'::int4range;

(来自https://www.postgresql.org/docs/9.3/static/rangetypes.html

你运气不好。但是,对此有一个功能请求,https://code.djangoproject.com/ticket/27147

Fwiw,psycopg2 支持所有范围边界类型。

选项?

  1. 一次性自定义 sql(恶心)
  2. 实现 Django 功能请求并提交 PR
  3. 只需使用 2 个 int 列(最快)
于 2017-06-24T20:06:48.900 回答