Skip to content Skip to sidebar Skip to footer

Django Rest Framework - Create Or Update Values From Json

I am very much new to Django and Django Rest Framework. I have an API whose json format is as below (Simplified version for sake of simplicity) { 'title' : 'Lorem ipsum is a du

Solution 1:

I think you can use Django's get_or_create() method as,

def create(self, validated_data):
    tags = validated_data.pop('tags')
    post = Post.objects.create(**validated_data)
    for tag in tags:
        tag_obj, create = Tag.objects.get_or_create(name=tag)
        post.tags.add(tag_obj)
    return post

The get_or_create() method will return a tuple of (object, created), where object is the retrieved or created object and created is a boolean specifying whether a new object was created.

Post a Comment for "Django Rest Framework - Create Or Update Values From Json"