GenericRelation
DRF に backrefrence を持つモデルを含めたい
ドキュメントは、これが簡単であることを示しています(すぐ上: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')
コメントアウトされた 2 つの行は、DRF にvoteable
内部でシリアル化する方法を伝える私の試みQuestion
です。
'GenericRelatedObjectManager' object has no attribute 'pk'
そして2番目
<django.contrib.contenttypes.fields.create_generic_related_manager.<locals>.GenericRelatedObjectManager object at 0x7f7f3756cf60> is not JSON serializable
だから、明らかに私は何かを誤解しています。