Marshall X
Marshall X

Reputation: 794

Django Rest Framework, model serializer, working with read only data

I have a endpoint like this: 'host.com/questions/123/vote'. front-end can send a post request with the vote type which is 'up' or 'down' to this endpoint. In the backend, vote is like this:

class Vote(models.Model):
UP = 'UP'
DOWN = 'DOWN'
CHOICE = ((UP, 'upvote'), (DOWN, 'downvote'))
post_content_type = models.ForeignKey(ContentType,
                                      on_delete=models.CASCADE)
post_id = models.PositiveIntegerField()
post = GenericForeignKey('post_content_type', 'post_id')
voter = models.ForeignKey(to=settings.AUTH_USER_MODEL,
                          related_name='votes')
type = models.CharField(choices=CHOICE, max_length=8)

class Meta:
    unique_together = ('post_content_type', 'post_id', 'voter')

I use generic fk because you can vote to different model instance besides Question too.

and now I create this api endpoint using DRF's CreateAPIView.

here is my question:

how do I pass in the data from both source: the request.data(where the vote type is), and the kwargs(where the question id, and the content type 'question').

I have tried:

  1. pass kwargs to self.get_serializer_context and get it via SerializerMethodField, didn't work
  2. pass kwrags directly to perform_create, but this pass the validation on drf side.

Upvotes: 0

Views: 713

Answers (2)

Marshall X
Marshall X

Reputation: 794

I end up override the to_internal function in the serializer, and pass the url data by overriding get_serializer_context in the CreateAPIView and get the data using self.context in the to_internal function

Upvotes: 0

Rob
Rob

Reputation: 877

You need to specify some write_only fields for post_content_type and post_id.

class VoteSerializer(serializers.Serializer):
    post_content_type_id = serializers.PrimaryKeyRelatedField(write_only=True)
    post_id = serializers.IntegerField(write_only=True)
    type = serializers.CharField()
    ## your other fields ...

If you're curious about how to output different representations for the generic relationship, take a look at this section of the DRF documentation: http://www.django-rest-framework.org/api-guide/relations/#generic-relationships.

Upvotes: 0

Related Questions