I want to include a model with a GenericRelation
backrefrence in DRF
The docs indicate this should be easy ( just above: http://www.django-rest-framework.org/api-guide/relations/#manytomanyfields-with-a-through-model ) - but I am missing something!
Note that reverse generic keys, expressed using the GenericRelation field, can be serialized using the regular relational field types, since the type of the target in the relationship is always known.
For more information see the Django documentation on generic relations.
my models:
class Voteable(models.Model):
content_type = models.ForeignKey(ContentType, on_delete=models.CASCADE)
object_id = models.PositiveIntegerField()
content_object = GenericForeignKey('content_type', 'object_id')
direct_vote_count = models.IntegerField(default=0)
class Question(models.Model):
user = models.ForeignKey(UserExtra, related_name='questions_asked')
voteable = GenericRelation(Voteable)
question = models.CharField(max_length=200)
and my serializers:
class VoteableSerializer(serializers.HyperlinkedModelSerializer):
class Meta:
model = Voteable
fields = ('pk', 'id', 'url', 'direct_vote_count')
class QuestionSerializer(serializers.HyperlinkedModelSerializer):
#voteable = VoteableSerializer(read_only=True, many=False)
#voteable = serializers.PrimaryKeyRelatedField(many=False, read_only=True)
class Meta:
depth = 1
model = Question
fields = ('url', 'question', 'user', 'voteable')
The two commented out lines are my attempts at telling DRF how to serialize voteable
inside Question
The first gives me
'GenericRelatedObjectManager' object has no attribute 'pk'
and the second
<django.contrib.contenttypes.fields.create_generic_related_manager.<locals>.GenericRelatedObjectManager object at 0x7f7f3756cf60> is not JSON serializable
So, clearly I am misunderstanding something, any idea what?