filter json data from Django model

First of all I create a admin user and two models

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"}

The second Tcu has two position data:

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

After that I create a view in order to get the last position of both TCUs.

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"}

How can I get both last position from first and second TCU ?


If I understand correctly, you want the last Position for each Tcu belonging to the current user ? If yes the following should work:

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

Someone might prove me wrong but I don't think there's a simple way to get what you want without iterating on the Tcu set...

Edit: if you have Tcu s without position , you may want to filter them out (preferably at the Queryset level) to avoid IndexError :

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
  ]
链接地址: http://www.djcxy.com/p/33744.html

上一篇: 可以Django restframework generics.ListCreateAPIView处理一个

下一篇: 从Django模型过滤json数据