Home > database >  how to do Django query that is ordered by latlng string
how to do Django query that is ordered by latlng string

Time:08-04

Current Situation

I Am fetching data that contains Strings that represent the Latlng of some locations .. like 30.78829892811801,31.2769004988329 30.78848118485095,31.27649189363398 30.78869531217787,31.27615745128788 etc.

What I have tried

now I am doing Django query like ModelName.objects.all().order_by('latlng') but it is not ordering it as the field is simply a Charfield .. also converting it to double is not working as it contains 2 different double separated by the comma.

What I need to do

Is there a way to convert this string to LatLng that is orderable by location or something like this?

CodePudding user response:

Are you using Postgres? If so, you can use the ArrayField to split out your string into an array that might make it more easily-sortable in the ORM.

from django.db.models import F, Value, DecimalField
from django.db.models.expressions import Func
from django.contrib.postgres.fields import ArrayField

latlng_arr_func = Func(
    F('latlng'),
    Value(","),
    function='regexp_split_to_array', output=ArrayField(DecimalField())
)

ModelName.objects.annotate(latlng_arr=latlng_arr_func).order_by('-latlng_arr')

Then calling object.latlng_arr should yield a list of your values [30.78829892811801,31.2769004988329].

If this doesn't get you the result you want then I would suggest either splitting the data into two decimal fields on your model (you could still keep the string version) or order the data using Python.

  • Related