Django Rest Framework make OnetoOne relation ship feel like it is one model

后端 未结 3 1908
时光取名叫无心
时光取名叫无心 2020-12-07 22:58

I have my User saved in two different models, UserProfile and User. Now from API perspective, nobody really cares that these two are d

3条回答
  •  一整个雨季
    2020-12-07 23:03

    I just came across this; I have yet to find a good solution particularly for writing back to my User and UserProfile models. I am currently flattening my serializers manually using the SerializerMethodField, which is hugely irritating, but it works:

    class UserSerializer(serializers.HyperlinkedModelSerializer):
    
        mobile = serializers.SerializerMethodField('get_mobile')
        favourite_locations = serializers.SerializerMethodField('get_favourite_locations')
    
        class Meta:
            model = User
            fields = ('url', 'username', 'first_name', 'last_name', 'email', 'mobile', 'favourite_locations')
    
        def get_mobile(self, obj):
            return obj.get_profile().mobile
    
        def get_favourite_locations(self, obj):
            return obj.get_profile().favourite_locations
    

    This is horribly manual, but you do end up with:

    {
        "url": "http://example.com/api/users/1",
        "username": "jondoe",
        "first_name": "Jon",
        "last_name": "Doe",
        "email": "jdoe@example.com",
        "mobile": "701-680-3095",
        "favourite_locations": [
            "Paris",
            "London",
            "Tokyo"
        ]
    }
    

    Which, I guess is what you're looking for.

提交回复
热议问题