簡體   English   中英

Django Rest Framework 序列化程序沒有得到 CharField

[英]Django Rest Framework serializer doesn't get CharField

我已經使用 Django 和 Django Rest Framework 構建了一個 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()

嘗試更改行:

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

對此:

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

由於添加了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) 

請嘗試“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

由於您使用的是帶點符號的序列化器字段, validated_data將是:

{
'geometrie': {'longitude': 4.58565, 'latitude': 52.0356}, 
'owner': {'organisation': 'Administration.'}
}

因此,您可以作為validated_data['owner']['organisation']訪問組織

但是,如果您想序列化另一個相關表/外鍵的屬性/列,您需要使用StringRelatedField [ organisation = serializers.StringRelatedField(source='owner.organisation') ] 這將確保instance fetched from the database contains the proper “設備instance fetched from the database contains the proper attribute during a GET` 請求attribute during a instance fetched from the database contains the proper組織attribute during a

但是反序列化不起作用,您需要在create方法中進行額外的實現。 這是因為您需要創建一個Person實例(與organisation ),然后將Device實例連接到該新創建的實例。

一個具體的例子可以在這里找到: 編寫嵌套序列化程序

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM