简体   繁体   English

处理django模型中的重复项

[英]Handling duplicates in django models

This is my location object 这是我的位置对象

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

This is the view in which I create a location, 这是我创建位置的视图,

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)

Now while saving the new location if the database throws duplication error, then I want to not write the new value but fetch the already existent data and return it as a success response message. 现在,如果数据库引发重复错误,在保存新位置的同时,我希望不写入新值,而是获取已存在的数据并将其作为成功响应消息返回。 In sense I want to add another else clause. 在某种意义上,我想添加另一个else子句。 I'm not sure how to do this in django. 我不知道如何在django中这样做。 Any help appreciated. 任何帮助赞赏。

what about get_or_create() ? get_or_create()怎么样?

see here for reference how it works https://docs.djangoproject.com/en/2.0/ref/models/querysets/#get-or-create 请参阅此处以了解其工作原理https://docs.djangoproject.com/en/2.0/ref/models/querysets/#get-or-create

be aware of possibility for using created to distinguish either it was just get or create new case: 要知道使用created来区分它只是getcreate new案例的可能性:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM