我想GenericRelation
在 DRF中包含一个带有后向参考的模型
文档表明这应该很容易(就在上面: http: //www.django-rest-framework.org/api-guide/relations/#manytomanyfields-with-a-through-model) - 但我错过了一些东西!
请注意,使用 GenericRelation 字段表示的反向通用键可以使用常规关系字段类型进行序列化,因为关系中目标的类型始终是已知的。
有关更多信息,请参阅有关泛型关系的 Django 文档。
我的模型:
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)
和我的序列化器:
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')
被注释掉的两行是我试图告诉 DRF 如何在voteable
里面序列化Question
第一行给了我
'GenericRelatedObjectManager' object has no attribute 'pk'
第二个
<django.contrib.contenttypes.fields.create_generic_related_manager.<locals>.GenericRelatedObjectManager object at 0x7f7f3756cf60> is not JSON serializable
所以,显然我误解了一些东西,知道什么吗?