简体   繁体   中英

How to annotate a Django QuerySet with a Point?

Lets say I have a model A that has fields lat(FloatField) and lon(FloatField). I want to annotate the QuerySet using a point:

A.objects.annotate(point = Value(Point(F('lat'), F('lon')), output_field=PointField()))

I keep on getting TypeError('Invalid parameters given for Point initialization.')

For some reason Django is not recognizing the fields and instead is passing them as strings (I think).

How do I accomplish this? Thanks

I personally believe you're better off writing a one time migration to add the point field rather than annotating this, but you are just passing strings ATM. You need to use F

A.objects.annotate(
    point=ExpressionWrapper(
        Point(F('lat'), F('lon')), output_field=PointField()))

ref: https://docs.djangoproject.com/en/3.0/ref/models/expressions/#using-f-with-annotations

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM