Search code examples
djangodjango-rest-frameworkdjango-templatesdjango-rest-viewsets

how can make new object in django-restful-framework by post method?


i have this model

class Product(models.Model):
    name = models.CharField(max_length=50)
    price = models.PositiveIntegerField()

i want make a new object using post method in restframework in django but i dont know what should i do please help me

@api_view(['POST'])
def create_product(request):
    *******
    return Response({
        *******
    }, status=status.HTTP_201_CREATED)

i should replace django code by **** please help me


Solution

  • Easy peasy. Mostly like the way you create new class objects in python.

    @api_view(['POST'])
    def create_product(request):
        p = Product(name='sth', price=1)
        p.save()
        return Response({
             # um... now we should start talking about serializers.
        }, status=status.HTTP_201_CREATED)
    

    Note that the method save() doesn't return the created object, so if you need the created objected just follow the pattern.

    As mutch as I know, the best way of sending a model object in respond (or even get an object data as request) is using serilizers. Serilizer in general means changing the format of data. Here in django, we can use serilizers as a tool to convert model objects to json. (In case you're not familiar with json data format, it's like a dictionary, both human readable and easy to deal with in programming.) Of course you can create your own json data (or dictionary) like this, too:

    data = {}
    data['name'] = p.name
    return Respond(data=data, 
    status=status.HTTP_201_CREATED)
    

    But why bother?

    Here's the link to drf's serializer documantary: https://www.django-rest-framework.org/api-guide/serializers/

    Enjoy!