5
class Foo(models.Model):
    bar = models.CharField(max_length=300)
    content_type = models.ForeignKey(ContentType)
    object_id = models.PositiveIntegerField()
    content_object = GenericForeignKey('content_type', 'object_id')


class FooSerializer(serializers.ModelSerializer):
    class Meta:
       model = Foo

class FooViewSet(viewsets.ModelViewSet):
    model = Foo
    serializer_class = FooSerializer

次のようなビューセットにデータを投稿できるようになりました。

{
    bar: 'content',
    content_type: 1
    object_id: 5
}

私を悩ませている唯一のことは、フロントエンドが contenttype id を認識しなければならないことです

代わりに、'User' のような content_types の名前を content_type として投稿し、バックエンドで ID を決定できるようにしたいと考えています。

4

3 に答える 3