简体   繁体   中英

How to update GeoDjango model with area fields

Here the model:

from django.contrib.gis.db import models    
class City(models.Model):
    mpoly = models.MultiPolygonField()
    area = models.IntegerField(null=True)

I want to update all records at once to set the area. I've tried:

from django.contrib.gis.db.models.functions import Area, Transform

City.objects.all().update(area=Area(Transform("mpoly", 2154)))

Which fails with "DataError: value too long for type character varying(8)"...

Do you have an elegant one liner to do it?

As a matter of fact, my problem was that I try to put a large number in a char field (of 8 characters). The provided example and the error are unrelated.

To make it work with the provided model:

from django.contrib.gis.db.models.functions import Area, Transform
from django.db.models import IntegerField
from django.db.models.functions import Cast

City.objects.all().update(area=Cast(Area(Transform("mpoly", 2154)), IntegerField()))

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