小编Jav*_*ero的帖子

访问DRF ListSerializer中的特定实例

我目前有要序列化的Django模型:

class Result(models.Model):
    ...
    routes = models.ManyToManyField(Route)
    ...

class Route(models.Model):
    ...

class Feature(models.Model):
    result = models.ForeignKey(Result)
    route = models.ForeignKey(Route)
    description = models.TextField()
Run Code Online (Sandbox Code Playgroud)

DRF序列化器如下所示:

class ResultSerializer(serializers.ModelSerializer):
    ...
    route = RouteSerializer(many=True, required=False)
    ...

    class Meta:
        model = Result
        fields = '__all__'

class FeatureField(serializers.CharField):
    """
    Accepts text in the writes and looks up the correct feature for the reads.
    """

    def get_attribute(self, obj):
        # We pass the object instance onto `to_representation`, not just the field attribute.
        return obj

    def to_representation(self, obj):
        try:
            search_result …
Run Code Online (Sandbox Code Playgroud)

python django django-rest-framework

1
推荐指数
1
解决办法
973
查看次数

标签 统计

django ×1

django-rest-framework ×1

python ×1