DRF:将GenericRelation限制为特定模型

时间:2018-06-10 17:05:17

标签: django django-models django-rest-framework

我正在寻找一种简洁的方法来限制某些ContentType对象的泛型关系。我无法在DRF的文档中找到相关信息(文档仍在追赶)。这是我的模型,视图和序列化器:

models.py

class OrderLine(models.Model):

    class Meta:
        verbose_name = _("Order line")
        verbose_name_plural = _("Order lines")

    content_type = models.ForeignKey(
        ContentType,
        on_delete=models.CASCADE
    )

    object_id = models.PositiveIntegerField()

    content_object = GenericForeignKey(
        'content_type',
        'object_id'
    )

views.py

class OrderLineViewSet(viewsets.ModelViewSet):
    serializer_class = serializers.OrderLineSerializer
    queryset = OrderLine.objects.all()
    permission_classes = (permissions.IsAdminOrReadOnly, IsAuthenticated)

serializers.py

class OrderLineSerializer(serializers.HyperlinkedModelSerializer):
    id = serializers.ReadOnlyField()
    content_type = serializers.SlugRelatedField(
        queryset=ContentType.objects.all(),
        slug_field='model',
    )

    class Meta:
        model = OrderLine
        fields = '__all__'

非常感谢任何建议。

0 个答案:

没有答案