【问题标题】:Django how to change bounds value of IntegerRangeFieldDjango如何更改IntegerRangeField的边界值
【发布时间】:2017-10-02 23:21:12
【问题描述】:

我有一个带有 IntegerRangeField 的模型,它返回数据,例如 NumericRange(1992, 1997, '[)') 将对象添加到数据库后。我需要范围的第二个选项也包含在其中,所以边界应该像 '[]'。 我在psycopg2 documentation 中寻找解决方案,但很遗憾没有找到答案。

请帮忙!提前致谢。

我目前的models.py

from django.contrib.postgres.fields import IntegerRangeField
from django.contrib.postgres.validators import RangeMinValueValidator, RangeMaxValueValidator
from django.core.validators import MinValueValidator, MaxValueValidator

from django.db import models
from datetime import datetime


class Bancnote(models.Model):

    Dollar= 'Dollar'
    Euro= 'Euro'

    TYPE_CHOICES = (
        (Dollar, 'Dollar'),
        (Euro, 'Euro')
    )

    type = models.CharField(max_length=11, choices=TYPE_CHOICES, default=Dollar)
    par = models.PositiveIntegerField()
    year = IntegerRangeField()
    size = models.CharField(max_length=7)
    sign = models.TextField(max_length=250)
    desc = models.TextField(max_length=500)
    image = models.ImageField(upload_to='bons_images')

    def __str__(self):
        return str(self.par) + ' ' + self.type + ' ' + str(self.year.lower) + '-' + str(self.year.upper)

【问题讨论】:

    标签: python django postgresql psycopg2


    【解决方案1】:

    官方documentation说:

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

    所以恐怕你无法真正改变这一点。但是,您可以照常存储数据:

    from psycopg2.extras import NumericRange
    
    Bancnote.objects.create(
        # specify other fields
        year=NumericRange(1992, 1997, bounds='[]')
    )
    # assuming the object we created is with id=1
    bancnote = Bancnote.objects.get(id=1)
    print(bancnote.year) # NumericRange(1992, 1998, '[)')
    

    我想你会这样做。帮助不大,但我能贡献的只有这些。

    【讨论】:

      猜你喜欢
      • 2017-11-27
      • 1970-01-01
      • 1970-01-01
      • 2018-03-13
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-02-22
      • 2016-09-01
      相关资源
      最近更新 更多