简体   繁体   中英

Saving User foreign key upon creation of related model

My Category model is related to User , but I can't find a way to store the logged in user's id into user_id field in Category .

Category models.py :

class Category(models.Model):
    user = models.ForeignKey(User, default=None)
    name = models.CharField(max_length=32, unique=True)

views.py :

class CategoryList(APIView):
    ...
    def post(self, request):
        """
        Create a new Category
        :param request:
        :return: Category
        """
        user_id = request.user.pk
        serializer = CategorySerializer(data=request.data)

        if serializer.is_valid():
            serializer.save()

            return Response(serializer.data, status=HTTP_201_CREATED)

        return Response(serializer.errors, status=HTTP_400_BAD_REQUEST)

I can access request.user.pk and see it's correctly shown, but I can't figure out how I can store this value when creating a new category.

To add current user id to new record you can pass current user as save argument:

if serializer.is_valid():
    serializer.save(user=request.user)

Or you can change serializer and use CurrentUserDefault :

user = serializers.HiddenField(default=serializers.CurrentUserDefault())

from docs:

A default class that can be used to represent the current user. In order to use this, the 'request' must have been provided as part of the context dictionary when instantiating the serializer.

So to use CurrentUserDefault you need to pass request to serializer in view:

serializer = CategorySerializer(data=request.data, context={'request': request})

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM