简体   繁体   中英

Specify django-rest-framework field for serializer after request?

I've got the following code:

models.py

class Interview(models.Model):
    id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False, help_text="The Primary Key of the Interview")
    organization = models.ForeignKey(Organization, on_delete=models.CASCADE, help_text="The Primary Key of the Organization in the interview")
    question = name = models.CharField(max_length=200, help_text="The Question")

serializers.py

class InterviewSerializer(serializers.ModelSerializer):
    class Meta:
        model = Interview
        fields = ('organization', 'question')

views.py

class InterviewViewset(viewsets.ModelViewSet):
    """
    API endpoint that allows Interviews to be viewed or edited.
    """
    serializer_class = InterviewSerializer

Right now, the request body to create an interview requires these fields:

{
  "organization": "string",
  "question": "string"
}

I'd like the organization for the Interview to automatically be set to the current users organization ( request.user.Organization - I've got a custom User model). How can I do this elegantly for my viewset?

One way (probably the best) is overriding save / create / update methods of your ModelSerializer class. DRF docs about it

There you can use self.context.get("request") to get current user. And if you still need organization field to be serialized, just make it read_only=True

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