使用 PointField 测试 django geoodel 导致 TypeError

Testing django geoodel with PointField results in TypeError

我有以下型号:

from django.contrib.gis.db import models as geo_model

class UserAddress(geo_model.Model):
    user = geo_model.OneToOneField(
        User, on_delete=models.CASCADE, related_name="user_address"
    )
    coordinates = geo_model.PointField()
    address = geo_model.CharField(max_length=255)
    city = geo_model.CharField(max_length=20)
    country = geo_model.CharField(max_length=20)

    def __str__(self):
        return self.name

现在,我正在尝试使用 pytest 对该模型进行单元测试:

@pytest.mark.django_db
class test_user_address():
    user_address = UserAddress(
        user=User(),
        address="my address",
        city="Oran",
        country="Algeria",
        coordinates=(7.15, 35.0)
    )
    user_address.save()

但是,这会导致以下错误:

TypeError: Cannot set SeekerAddress SpatialProxy (POINT) with value of type: <class 'tuple'>

我应该如何在坐标中传递数据类型?

您需要使用 django.contrib.gis.geos Point 的实例。

所以您的测试的正确代码是:

coordinates=Point(7.15, 35.0) # you can use tuple if you prefer but it's not mandatory

所以我找到了一个临时解决方案,我应该使用 Point 而不是 tuple。我认为 PointField 会接受一个元组并将其转换为 Point.

基本上,这是我所做的:

@pytest.mark.django_db
def test_user_address():
    user= User()
    user.save()
    user_address = UserAddress(
        user=user,
        address="my address",
        city="Oran",
        country="Algeria",
        coordinates=Point(7.15, 35.0)
    )
    user_address.save()