Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/279.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 在django模型中处理重复项_Python_Django - Fatal编程技术网

Python 在django模型中处理重复项

Python 在django模型中处理重复项,python,django,Python,Django,这是我的位置对象 class Location(models.Model): country = models.CharField(max_length=255) city = models.CharField(max_length=255, unique=True) latitude = models.CharField(max_length=255) longitude = models.CharField(max_length=255) class

这是我的位置对象

class Location(models.Model):
    country = models.CharField(max_length=255)
    city = models.CharField(max_length=255, unique=True)
    latitude = models.CharField(max_length=255)
    longitude = models.CharField(max_length=255)

    class Meta:
        unique_together = ('country', 'city')
这是我创建位置的视图

class LocationView(views.APIView):
    def post(self, request):
        serializer = LocationSerializer(data=request.data)
        if serializer.is_valid():
            serializer.save()
            return Response(serializer.data, status=status.HTTP_201_CREATED)
        else:
            Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)
现在,在保存新位置时,如果数据库抛出复制错误,那么我不想写入新值,而是获取已经存在的数据,并将其作为成功响应消息返回。从某种意义上说,我想添加另一个else子句。我不知道在django怎么做。
非常感谢您的帮助。

关于
获取或创建()

请参见此处以了解其工作原理

注意使用
created
来区分它是否只是
get
createnew
案例的可能性:

obj, created = Person.objects.get_or_create(
    first_name='John',
    last_name='Lennon',
    defaults={'birthday': date(1940, 10, 9)},
)