GenericForeignKey, ContentType and DjangoRestFramework

I am working on a discussion application in Django that has topics, posts, answers and voices. Votes use Common foreign keys and content types to ensure that the user can vote only once for a specific topic / message / response.

The voting model is as follows:

VOTE_TYPE = ( (-1, 'DISLIKE'), (1, 'LIKE'), ) class Vote(models.Model): user = models.ForeignKey(User) content_type = models.ForeignKey(ContentType, limit_choices_to={"model__in": ("Thread", "Reply", "Post")}, related_name="votes") object_id = models.PositiveIntegerField() content_object = generic.GenericForeignKey('content_type', 'object_id') vote = models.IntegerField(choices=VOTE_TYPE) objects = GetOrNoneManager() class Meta(): unique_together = [('object_id', 'content_type', 'user')] 

Vote Serializer:

 class VoteSerializer(serializers.ModelSerializer): class Meta: model = Vote 

Voting outlook:

 @api_view(['POST']) def discussions_vote(request): if not request.user.is_authenticated(): return Response(status=status.HTTP_404_NOT_FOUND) data = request.DATA if data['obj_type'] == 'thread': content_type = ContentType.objects.get_for_model(Thread) print content_type.id info = { 'content_type': content_type.id, 'user': request.user.id, 'object_id': data['obj']['id'] } vote = Vote.objects.get_or_none(**info) info['vote'] = data['vote'] ser = VoteSerializer(vote, data=info) if ser.is_valid(): print "Valid" else: pprint.pprint(ser.errors) return Response() 

request.DATA:

 {u'vote': -1, u'obj_type': u'thread', u'obj': { ... u'id': 7, ... } } 

When I vote, the Django Rest Framework serializer throws an error:

 Model content type with pk 149 does not exist. 

149 - the correct identifier for ContentType for the Thread model, according to

 print content_type.id 

I hardly understand what could cause this ...

+6
source share
1 answer

Probably the problem is that you have a shared foreign key that can be associated with any type of model instance, so there is no default method for the REST structure that defines how to represent serialized data.

Take a look at the GFK docs in serializers here, hope this helps you get started ... http://www.django-rest-framework.org/api-guide/relations#generic-relationships

If you still find this problematic, just give up the use of serializers in general and just check the view correctly and return a dictionary of any values โ€‹โ€‹you want to use for the view.

+4
source

All Articles