Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to create a created_by field in django rest framework model?

I want to create a created_by field in django rest framework model.

It should contain, user_id of currently logged in user and it should be such that I need not send it during POST request in JSON format, it should be taken from request itself, how can I implement it using django rest framework serializer.

models.py file:

class Company(models.Model):
    """Company model for information about company."""

    created_by = models.ForeignKey(User, null= True, blank= True, on_delete=models.CASCADE)
    company_name = models.CharField(max_length=100)

serializers.py file:

class CompanySerializer(serializers.ModelSerializer):
"""Serializer for companies."""

    class Meta:
        model = Company
        fields = ('id', 'created_by', 'company_name')

v1.py file:

class CompanyList(APIView):
"""Get and post companies data."""

    def get(self, request, format=None):
        """Get companies data.."""
        companies = Company.objects.all()
        serialized_companies = CompanySerializer(companies, many=True)
        return Response(serialized_companies.data)

    def post(self, request, format=None):
        """Post companies data."""
        serializer = CompanySerializer(data=request.data)
        if serializer.is_valid():
            serializer.save()
            return Response(serializer.data, status=status.HTTP_201_CREATED)
        return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)
like image 667
Ankit Avatar asked Jun 06 '16 10:06

Ankit


People also ask

How do you save a foreign key field in Django REST framework?

Your code is using serializer only for validation, but it is possible use it to insert or update new objects on database calling serializer. save() . To save foreign keys using django-rest-framework you must put a related field on serializer to deal with it. Use PrimaryKeyRelatedField .

What is serializer method field in django?

Serializers in Django REST Framework are responsible for converting objects into data types understandable by javascript and front-end frameworks. Serializers also provide deserialization, allowing parsed data to be converted back into complex types, after first validating the incoming data.

What is the difference between ModelSerializer and HyperlinkedModelSerializer?

The HyperlinkedModelSerializer class is similar to the ModelSerializer class except that it uses hyperlinks to represent relationships, rather than primary keys. By default the serializer will include a url field instead of a primary key field.


2 Answers

Method-1: Using CurrentUserDefault() option

You can pass default parameter in created_by field as serializers.CurrentUserDefault() which will set its value as the current user.

class CompanySerializer(serializers.ModelSerializer):
"""Serializer for companies."""

    class Meta:
        model = Company
        fields = ('id', 'created_by', 'company_name')
        extra_kwargs = {'created_by': {'default': serializers.CurrentUserDefault()}}

Method-2: Passing user in serializer.save()

You can set the field created_by as read_only and then pass request.user to serializer.save().

serializers.py

class CompanySerializer(serializers.ModelSerializer):
"""Serializer for companies."""

    class Meta:
        model = Company
        fields = ('id', 'created_by', 'company_name')
        extra_kwargs = {'created_by': {'read_only':True}}

v1.py

class CompanyList(APIView):
"""Get and post companies data."""

    def post(self, request, format=None):
        """Post companies data."""
        serializer = CompanySerializer(data=request.data)
        if serializer.is_valid():
            serializer.save(created_by=request.user) # pass current user
            return Response(serializer.data, status=status.HTTP_201_CREATED)
        return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)
like image 173
Rahul Gupta Avatar answered Oct 14 '22 20:10

Rahul Gupta


You can just use serializers.CurrentUserDefault() as default for the created_by field in the CompanySerializer and make that field read_only=True.

See the docs here.

like image 28
Ivan Genchev Avatar answered Oct 14 '22 21:10

Ivan Genchev