如何检查UUID是否存在



我试图检查在我的Django环境中是否存在UUID作为主键…当它存在的时候……我的代码工作得很好…但如果它不存在,我就会得到一个"不是一个有效的UUID…

这是我的代码....

uuid_exists = Book.objects.filter(id=self.object.author_pk,is_active="True").first()

我用。exists()或。all()尝试了其他的变体…但我一直得到的[' " "不是一个有效的UUID。']错误。

我确实想出了一个解决办法....

if self.object.author_pk is not '':
book_exists = Book.objects.filter(id=self.object.author_pk,is_active="True").first()
context['author_exists'] = author_exists

这是最好的方法吗?我希望能使用直滤镜……不讲逻辑....但我已经工作了一下午,似乎也想不出更好的办法。提前感谢任何反馈或意见。

我有同样的问题,这就是我所拥有的:
包装它到try/except(在我的情况下,它是一个视图,所以它应该返回一个Response对象)

try:
object = Object.objects.get(id=object_id)
except Exception as e:
return Response(data={...}, status=status.HTTP_40...

它到达异常(第4行),但不知何故发送'~your_id~' is not a valid UUID.文本而不是正确的数据。在某些情况下,这可能就足够了。

这似乎是一个疏忽,所以最好尽快修复。遗憾的是,我没有足够的时间深入调查。

所以我想出的解决方案也不是理想的,但希望比你使用的rn更干净,更快。

# Generate a list of possible object IDs (make use of filters in order to reduce the DB load)
possible_ids = [str(id) for id in Object.objects.filter(~ filters here ~).values_list('id', flat=True)]
# Return an error if ID is not valid
if ~your_id~ not in possible_ids:
return Response(data={"error": "Database destruction sequence initialized!"}, status=status.HTTP_401_UNAUTHORIZED)
# Keep working with the object
object = Objects.objects.get(id=object_id)

相关内容

最新更新