我使用Django和Django Rest框架构建了一个API。在我的序列化程序中,我定义了一个organisation
,它可以发布,但需要存储到不同的模型中。我将序列化程序定义如下:
class DeviceSerializer(serializers.HyperlinkedModelSerializer):
geometrie = PointField(required=False)
organisation = serializers.CharField(source='owner.organisation')
owner = PersonSerializer(required=False)
class Meta:
model = Device
fields = (
'id',
'geometrie',
'longitude',
'latitude',
'organisation',
'owner',
)
def get_longitude(self, obj):
if obj.geometrie:
return obj.geometrie.x
def get_latitude(self, obj):
if obj.geometrie:
return obj.geometrie.y
def create(self, validated_data):
print("ORG:", validated_data.get('organisation', "NO ORG FOUND")) #
# Do some custom logic with the organisation here
但是当我向它发布一些json时,它包含一个organisation
(我对输入进行了三次检查),它会打印出ORG: NO ORG FOUND
行。你知道吗
它究竟为什么不推进组织?你知道吗
[编辑]
型号代码:
class Person(models.Model):
name = models.CharField(max_length=255)
email = models.EmailField()
organisation = models.CharField(max_length=250, null=True, blank=True)
class Device(models.Model):
geometrie = gis_models.PointField(name='geometrie', null=True, blank=True)
owner = models.ForeignKey(to='Person', on_delete=models.SET_NULL, null=True, blank=True, related_name='owner')
以及测试代码:
def test_full_post(self):
device_input = {
"geometrie": {"longitude": 4.58565, "latitude": 52.0356},
"organisation": "Administration."
}
url = reverse('device-list')
self.client.force_login(self.authorized_user)
response = self.client.post(url, data=device_input, format='json')
self.client.logout()
请尝试“StringRelatedField”。你知道吗
由于添加了
source
参数,DRF会自动将organisation
数据推送到嵌套级别因此,如果要访问组织数据,请尝试以下操作:
尝试更改行:
对此:
相关问题 更多 >
编程相关推荐