gpt4 book ai didi

django - get_or_create 对于小数的 unique_together 失败

转载 作者:行者123 更新时间:2023-12-03 03:38:24 33 4
gpt4 key购买 nike

我有以下模型:

class LocationPoint(models.Model):
latitude = models.DecimalField(max_digits=9, decimal_places=6)
longitude = models.DecimalField(max_digits=9, decimal_places=6)

class Meta:
unique_together = (
('latitude', 'longitude',),
)

交互者:

class GetOrCreateLocationPoint(object):

def exec(self, latitude: Decimal, longitude: Decimal) -> LocationPoint:
point, _ = LocationPoint.objects.get_or_create(
latitude=latitude,
longitude=longitude,

defaults={
'latitude': latitude,
'longitude': longitude,
},
)

return point

并测试:

class GetOrCreateLocationPointTest(TestCase): # from django.test import TestCase
__get_or_create_location_point: GetOrCreateLocationPoint

def setUp(self) -> None:
self.__get_or_create_location_point = GetOrCreateLocationPoint()

def test_create_duplicate(self):
point1 = self.__get_or_create_location_point.exec(Decimal(10.5), Decimal(5.01))
self.__get_or_create_location_point.exec(Decimal(13.4), Decimal(1.5343))
point3 = self.__get_or_create_location_point.exec(Decimal(10.5), Decimal(5.01))

self.assertEqual(point1.pk, point3.pk)

执行point3 = self.__get_or_create_location_point.exec(Decimal(10.5), Decimal(5.01))时出错:

django.db.utils.IntegrityError: duplicate key value violates unique constraint "geo_locationpoint_latitude_longitude_08fb2a82_uniq"
DETAIL: Key (latitude, longitude)=(10.500000, 5.010000) already exists.

但是,如果在调试器中我看到 self.model.DoesNotExistget_or_create 中抛出(并处理),因此它找不到现有行。

出了什么问题?

Django 3.0.3、PostgreSQL 12。

最佳答案

好吧,由于在 Decimal 构造函数中使用 float ,它似乎失败了......

用字符串表示替换 float 解决了这个问题:

    def test_create_duplicate(self):
point1 = self.__get_or_create_location_point.exec(Decimal('10.5'), Decimal('5.01'))
self.__get_or_create_location_point.exec(Decimal('13.4'), Decimal('1.5343'))
point3 = self.__get_or_create_location_point.exec(Decimal('10.5'), Decimal('5.01'))

self.assertEqual(point1.pk, point3.pk)

关于django - get_or_create 对于小数的 unique_together 失败,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60197359/

33 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com