gpt4 book ai didi

python - 从 Django 模型中过滤 json 数据

转载 作者:行者123 更新时间:2023-12-01 04:19:14 24 4
gpt4 key购买 nike

首先,我创建一个管理员用户和两个模型

class Tcu    user = models.ForeignKey(User)    imei = models.CharField(max_length=30, unique=True)class Position    tcu = models.ForeignKey(Tcu)    latitude = models.CharField(max_length=30)    longitude = models.CharField(max_length=30)    gps_date = models.CharField(max_length=20)    speed = models.CharField(max_length=10, null=True, blank=True)    heading = models.CharField(max_length=10, null=True, blank=True)

After that I manually assign my admin user to two TCUs.

The first Tcu has three position data:

{"latitude": "21", "longitude": "21"}, {"latitude": "22", "longitude": "22"}, {"latitude": "23", "longitude": "23"}

第二个 Tcu 有两个位置数据:

{"latitude": "10", "longitude": "10"}, {"latitude": "11", "longitude": "11"}

之后,我创建一个 View 以获取两个 TCU 的最后位置。

def tcu_position(request):        current_user_id = request.user.id        tcu_pos = Position.objects.filter(tcu_id__user_id=current_user_id).values('latitude', 'longitude').order_by('-id')[:1:1]        return JsonResponse ({'json_position_list': list(tcu_pos)})

The result is that I only get the last position of the second TCU:

{"latitude": "11", "longitude": "11"}

如何从第一个和第二个 TCU 获取最后位置?

最佳答案

如果我理解正确的话,您想要属于当前用户的每个 Tcu 的最后一个位置吗?如果是的话,以下应该可以工作:

positions = [
tcu.position_set.order_by('-id').values('latitude','longitude')[0]
for tcu in request.user.tcu_set.prefetch_related('position_set')
]

有人可能会证明我错了,但我不认为有一种简单的方法可以在不迭代 Tcu 集的情况下获得你想要的东西......

编辑:如果您的 Tcu 没有 position,您可能需要将它们过滤掉(最好在 Queryset 级别)以避免索引错误:

tcus =  request.user.tcu_set.exclude(position_set__isnull=True).prefetch_related('position_set')
positions = [
tcu.position_set.order_by('-id').values('latitude','longitude')[0]
for tcu in tcus
]

关于python - 从 Django 模型中过滤 json 数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33916150/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com