Home > Net >  Update django model database with ForeignKey by using serializer
Update django model database with ForeignKey by using serializer

Time:04-06

I have created a django model which includes a foreign key to a user as follows:

from authentication.models import User
from django.db import models

class Event(models.Model):
    
    user = models.ForeignKey(User, on_delete=models.CASCADE, null=True)
    dr_notice_period = models.IntegerField(blank=True, null=True)
    dr_duration = models.IntegerField(blank=True, null=True)
    dr_request = models.FloatField(blank=True, null=True)

My serializers.py file is as follows:

class EventSerializer(serializers.ModelSerializer):

    user = UserSerializer(many=True, read_only=True)

    class Meta:
        model = Event
        fields = ['user', 'dr_notice_period', 'dr_duration', 'dr_request']

What I need to do is to go to a url and with a POST request to upload the data to the database, but without specifically specifying the user.

My views.py is as follows:

from rest_framework.response import Response
from rest_framework.decorators import api_view
from rest_framework import status

from vpp_optimization.serializers import EventSerializer

@api_view(['POST'])
def event(request):

    serializer = EventSerializer(data=request.data)

    if serializer.is_valid():
        instance = serializer.save(commit=False)
        instance.user = request.user
        instance.save()
        return Response({"status": "success", "data": serializer.data}, status=status.HTTP_200_OK)
    else:
        return Response({"status": "error", "data": serializer.errors}, status=status.HTTP_400_BAD_REQUEST)

As I study I thought that by using commit=False in save would solve the problem, but I am getting the following error:

'commit' is not a valid keyword argument to the 'save()' method. If you need to access data before committing to the database then inspect 'serializer.validated_data' instead. You can also pass additional keyword arguments to 'save()' if you need to set extra attributes on the saved model instance. For example: 'serializer.save(owner=request.user)'.'

Is there a better way to do what I intent to do?

CodePudding user response:

You pass the user as parameter, so:

if serializer.is_valid():
    instance = serializer.save(user=request.user)
        return Response({'status': 'success', 'data': serializer.data}, status=status.HTTP_200_OK)

Note: It is normally better to make use of the settings.AUTH_USER_MODEL [Django-doc] to refer to the user model, than to use the User model [Django-doc] directly. For more information you can see the referencing the User model section of the documentation.

  • Related