这个问题可能看起来很多余,但是我已经搜索了其他答案,但他们似乎并没有解决问题。我正在使用带有DRF3的GeoDjango。我的模型中有一个名为location的字段,其值指定为Point实例,该实例以经度和纬度为参数。
因此,在序列化程序中,我有两个非模型字段-纬度和经度。但是,当我打印validated_data
时,lat和lng不会反序列化。
我已为模型serialzerMethodField
和latitude
移除了longitude
,并用location
字段替换了它们。
models.py
class Site(models.Model):
site_id = models.UUIDField(default=uuid.uuid4, editable=False, primary_key=True)
owner = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE, related_name="site")
location = models.PointField(geography=True, null=True, blank=True)
area = models.FloatField(null=True)
objects = SiteManager()
managers.py
class SiteManager(BaseManager):
use_in_migrations = True
def create(self, owner, **kwargs):
print('kwargs is ',kwargs)
site = self.model(
owner = owner,
area = kwargs['area'],
location=Point(float(kwargs['location']['latitude']), float(kwargs['location']['longitude'])),
)
site.save(using=self._db)
print('site is ',site)
return site
serializers.py
class SiteSerializer(serializers.ModelSerializer):
class Meta:
model = Site
fields = ('location', 'area')
# Serializer to get user details
class UserSiteSerializer(serializers.ModelSerializer):
site = SiteSerializer()
class Meta:
model = User
fields = ('fullName', 'email', 'site')
def create(self, validated_data):
site_data = validated_data.pop('site')
user = InterestedUser.objects.create(**validated_data)
Site.objects.create(owner=user, **site_data)
return user
请求数据为:
{'fullName': 'rtyhgf', 'email': '8sdfggfs@er.com', 'site': {'location': {'longitude': 72.81919139881033, 'latitude': 18.925400020910235}, 'area': 636.865234375}
当我以site_data
的{{1}}方法打印create
时,我得到UserSiteSerializer
答案 0 :(得分:0)
SerializerMethodField
用于只读字段。您应该像这样编写序列化器。
class SiteSerializer(serializers.ModelSerializer):
latitude = serializers.FloatField(source='get_latitude')
longitude = serializers.FloatField(source='get_longitude')
def get_latitude(self, validated_data):
print(validated_data['latitude'])
def get_longitude(self, validated_data):
print(validated_data['longitude'])
class Meta:
model = Site
fields = ('latitude', 'longitude', 'area')