python - 有没有办法在 Django ORM 的 Case-When 查询中使用任何用户定义的 Python 方法?
问题描述
我已经定义了一个类及其必要的方法,如下所示。
class Location(models.Model):
latitude = models.DecimalField(max_digits=20, decimal_places=8, default=Decimal("0.00"), null=True)
longitude = models.DecimalField(max_digits=20, decimal_places=8, default=Decimal("0.00"), null=True)
@staticmethod
def prepare_location_hotlink(latitude=None, longitude=None):
returm mark_safe(s="<a class='inline-link' href='https://maps.google.com/maps?z=17&q={lat},{lng}' target='_blank'>{lat}, {lng}</a>".format(lat=latitude, lng=longitude))
@classmethod
def retrieve_location_data(cls):
annotated_case_query = {
"location": Case(
When(Q(location__isnull=False, longitude__isnull=False),
then=cls.prepare_location_hotlink(latitude=F("latitude"), longitude=F("longitude"))
), default=Value("Not Available"), output_field=CharField()
)
}
return [loc for loc in cls.objects.annotate(**annotated_case_query).values_list("location", flat=True)]
在这里,在retrieve_location_data
方法中,我尝试在查询中使用用户定义的( prepare_location_hotlink
) Python 方法Case
来检索所有作为热链接的位置数据。似乎不能以上述方式工作。但无论如何我都需要在查询中使用用户定义的python 方法Case
,因为它检索和准备数据的速度要快得多。我已经研究并阅读了Django
文档,但不幸的是,我找不到这种情况的任何解决方案。
关于如何在查询中使用任何用户定义的Python 方法,是否有任何适当且准确的方法?Case
Django ORM
解决方案
您可以使用该Concat
函数在数据库级别连接您的字符串,但是,在这种情况下,我会选择@Willem Van Onsem 答案,它更具可读性和可维护性。
您还可以包装您的查询集list()
以使其成为一个列表。
from django.db.models import Q, Case, When, Value, F
from django.db.models.functions import Concat
annotated_case_query = {
"location": Case(
When(Q(location__isnull=False, longitude__isnull=False),
then=Concat(Value("<a class='inline-link' href='https://maps.google.com/maps?z=17&q="), F("latitude"), Value(","), F("longitude"), Value("' target='_blank'>"), F("latitude"), Value(", "), F("longitude"), Value('</a>'))
), default=Value("Not Available"), output_field=CharField()
)
}
return list(cls.objects.annotate(**annotated_case_query).values_list("location", flat=True))
推荐阅读
- java - 如何生成随机字节,然后在 Swift 中将它们转换为字符串
- r - 使用 R 中的矢量化代码比较和替换多列之间的值
- python - 进程以 Python 中的退出代码 -1073741571 (0xC00000FD) 完成
- javascript - 我可以使用 Google Apps 脚本将 Google 表格中的条件格式注入 Google 幻灯片吗?
- python - 修改数据集的某些元素时发出警告
- python - 矩阵大小不兼容:In[0]: [32,97], In[1]: [121,80] [[{{node dense_46/Relu}}]]
- flutter - Flutter 中 GlobalKey 的 currentState 为空
- python - PySpark:在 n 个元素上做一个简单的滑动窗口并通过函数聚合
- javascript - chrome.identity.launchWebAuthFlow 不起作用,但 chrome.identity.getAuthToken 工作
- android - 如何在关闭活动后停止继续播放的媒体播放器