Django如何更改integerangeField的边界值

2024-06-12 15:00:10 发布

您现在位置:Python中文网/ 问答频道 /正文

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

请帮忙!提前谢谢。在

我的电流模型.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)

Tags: djangofrom模型importselfmodelspostgrescontrib
1条回答
网友
1楼 · 发布于 2024-06-12 15:00:10

官员说:

Regardless of the bounds specified when saving the data, PostgreSQL always returns a range in a canonical form that includes the lower bound and excludes the upper bound; that is [).

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

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, '[)')

我想你会的。这帮不了什么忙,但我能做的就是这些。在

相关问题 更多 >