Django Rest框架序列化程序未获取CharField

2024-09-25 00:30:48 发布

您现在位置:Python中文网/ 问答频道 /正文

我使用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()

Tags: orgselftrueobjdatagetmodelsdef
3条回答

请尝试“StringRelatedField”。你知道吗

class DeviceSerializer(serializers.HyperlinkedModelSerializer):

    geometrie = PointField(required=False)
    organisation = serializers.CharField(source='owner.organisation')  # yours
    # ----------------
    organisation = serializers.StringRelatedField(source='owner.organisation')  # try this.
    owner = PersonSerializer(required=False)

    # your code

由于添加了source参数,DRF会自动将organisation数据推送到嵌套级别
因此,如果要访问组织数据,请尝试以下操作:

class DeviceSerializer(serializers.HyperlinkedModelSerializer):
    organisation = serializers.CharField(source='owner.organisation')

    # other code stuffs
    def create(self, validated_data):
        organisation = validated_data['owner']['organisation']
        print("ORG:", organisation) 

尝试更改行:

print("ORG:", validated_data.get('organisation'], "NO ORG FOUND")) 

对此:

print("ORG:", validated_data.get('organisation', "NO ORG FOUND"))

相关问题 更多 >