CraigH
CraigH

Reputation: 2061

Django Rest Framework: How to Append to array

I have a user object where I want to add a new friend onto their existing friends list. If below is the existing friends list for user1 , how would I POST/PUT a new friend onto that existing list without reposting the whole friends list.

    {
        "friends": [
            {
                "first_name": "Bob" 
            },
            {
                "first_name": "Dave" 
            },
            {
                "first_name": "Jon" 
            }

        ],
       "first_name": "User1", 
    }

What would my JSON look like in the POST and what do I have to do on the DRF end to allow me to update this array without reposting the existing array.

I tried to POST the following but it just overwrote the entire friend list

PATCH /api/profile/55522221111/ HTTP/1.1
{"friends":[{"first_name":"new friend"}]}

Upvotes: 0

Views: 1623

Answers (2)

Francisco
Francisco

Reputation: 2056

An alternative to your strategy could be redefining your models so as to create a one-to-many reference of the inner objects in the array, which in your example has {"first_name": "Bob"} in it to the main object.

This would allow you to post into the friends array just by mentioning a foreign key in model.

Something like :

models.py

class User(models.Model):
    first_name    = models.CharField(max_length=64)

class Friend(models.Model):
    first_name    = models.CharField(max_length=64)
    user          = models.ForeignKey(User, related_name='friends')

serializers.py

class FriendSerializer(serializers.ModelSerializer):

    class Meta:
        model = Friend
        fields = ('id', 'first_name', )


class UserSerializer(serializers.ModelSerializer):
    friends = FriendSerializer(many=True)

    class Meta:
        model = User
        fields = ('id', 'first_name', 'friends', )

views.py

class UserViewSet(viewsets.ModelViewSet):
    queryset = User.objects.all()
    serializer_class = UserSerializer

class FriendViewSet(viewsets.ModelViewSet):
    queryset = User.objects.all()
    serializer_class = FriendSerializer

urls.py

router = routers.DefaultRouter()
router.register(r'users', UserViewSet)
router.register(r'friends', FriendViewSet)

urlpatterns = [
    url(r'^api/', include(router.urls)),
]

This should result in 2 urls like (1) /api/users/ and (2) /api/friends/ and you can post into (2) and if references are correct it will show as you wish in (1).

{
    "friends": [
        {
            "first_name": "Bob" 
        },
        {
            "first_name": "Dave" 
        },
        {
            "first_name": "Jon" 
        }

    ],
   "first_name": "User1", 
}

Upvotes: 1

Kevin Stone
Kevin Stone

Reputation: 8981

You'd be better off creating a new endpoint, something like:

POST /api/profile/555222211111/friends/add/
{
    "first_name": "new_friend"
}

Upvotes: 0

Related Questions