Search code examples
djangoserializationdjango-rest-framework

how can i update two model table fields at one request in django rest api


i have two tables called user and address. the address table have a foreign key relation with the user table. so how access the fields of both table and update it in a single request call

{
    "first_name": "abijith",
    "last_name": "manu",
    "profile_picture": "http://127.0.0.1:8000/media/profile_pictures/my_pic_RxnXQ6n.jpg",
    "date_of_birth": "2024-02-16",
    "username": "",
    "gender": "male",
    "email": "doc@gmail.com",
    "phone_number": "7306986870",
    "addresses": [
        {
            "street": "xvsvf",
            "city": "sss",
            "state": "ssss",
            "country": "ggggggggg",
            "zip_code": "sssssss"
        }
    ]

this is the sample form of response that i want. and i have to update the filed as well


Solution

  • You can archive those thigs using nested serializer

    serializers.py

    from rest_framework import serializers
    
    class AddressSerializer(serializers.ModelSerializer):
        class Meta:
            model = Address
            fields = ['street', 'city', 'state', 'country', 'zip_code']
    
    class UserSerializer(serializers.ModelSerializer):
        addresses = AddressSerializer(many=True)
    
        class Meta:
            model = User
            fields = ['first_name', 'last_name', 'profile_picture', 'date_of_birth', 'username', 'gender', 'email', 'phone_number', 'addresses']
    
        def create(self, validated_data):
            addresses_data = validated_data.pop('addresses')
            user = User.objects.create(**validated_data)
            for address_data in addresses_data:
                Address.objects.create(user=user, **address_data)
            return user
    
        def update(self, instance, validated_data):
            addresses_data = validated_data.pop('addresses')
            instance = super(UserSerializer, self).update(instance, validated_data)
    
            # Assuming you don't want to add new addresses, but update existing ones
            for address_data in addresses_data:
                address_instance = instance.addresses.get(pk=address_data.get('id'))
                AddressSerializer().update(address_instance, address_data)
    
            return instance
    

    views.py

    class UserUpdateView(generics.UpdateAPIView):
        queryset = User.objects.all()
        serializer_class = UserSerializer