Django序列化器显示相关模型的BooleanField

时间:2019-05-03 12:19:28

标签: python django django-rest-framework

上下文

我有2个模型:AppAppVersion

我正在尝试将AppVersion模型中的字段与App模型中的字段进行序列化。我无法在序列化器中显示相关字段。

目标

我的目标是让API响应包含如下相关字段:

[
    {
        "app_version_uuid": "61ee8efa-f79e-4fcd-a6ea-4a33544442e1",
        "app_version_name": "Test app version",
        "version_code": 2,
        "version_name": "0.2",
        "auto_start": True   # related field
    }
]

模型

# models.py

class App(models.Model):
    app_uuid = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False, db_index=True)
    app_name = models.CharField(max_length=100)
    package_id = models.CharField(max_length=100, unique=True, null=True, blank=True, editable=False)
    auto_start = models.BooleanField(default=False)  


class AppVersion(models.Model):
    app_version_uuid = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False, db_index=True)
    app_uuid = models.ForeignKey(App, on_delete=models.CASCADE, related_name='app_versions')
    app_version_name = models.CharField(max_length=100)
    version_name = models.CharField(blank=True, null=True, max_length=100, editable=False)
    version_code = models.IntegerField(blank=True, null=True, editable=False)

序列化器

# serializers.py

class AppVersionSerializer(serializers.ModelSerializer):
    auto_start = serializers.SlugRelatedField(read_only=True, slug_field='auto_start')

    class Meta:
        model = AppVersion
        fields = ('app_version_uuid', 'app_version_name', 'version_code', 'version_name', 'auto_start')

我尝试过的

我尝试使用SlugRelatedField()中所示的serializers.py。我还尝试过使用SerializerMethodField()

# serializers.py

class AppSerializer(serializers.ModelSerializer):
    class Meta:
        model = App
        fields = ('auto_start')

class AppVersionSerializer(serializers.ModelSerializer):
    auto_start = serializers.SerializerMethodField(read_only=True)

    def get_auto_start(self, model):
        return AppSerializer(model).data

    class Meta:
        model = AppVersion
        fields = ('app_version_uuid', 'app_version_name', 'version_code', 'version_name', 'auto_start')

SlugRelatedField()在响应中未显示auto_start

使用SerializerMethodField() auto_start显示为:

"auto_start": {}

为了在响应中获得相关字段auto_start,我需要更改什么?

1 个答案:

答案 0 :(得分:3)

source参数与BooleanField一起使用,

class AppVersionSerializer(serializers.ModelSerializer):
    auto_start = serializers.BooleanField(source='app_uuid.auto_start')

    class Meta:
        model = AppVersion
        fields = ('app_version_uuid', 'app_version_name', 'version_code', 'version_name', 'auto_start')