如何在Django中使用序列化器将合并两个字段合并为一个字段

xytpbqjk  于 2023-10-21  发布在  Go
关注(0)|答案(1)|浏览(216)

是否可以合并两个字段,例如,age_fromage_to到名为age的键和字典值。就像这样:

age : {
    from: 18,
    to: null
}

我的模特:

# models.py

class Banner(models.Model):
    text = models.CharField(max_length=255)
    description = models.TextField()
    image = WEBPField(
        verbose_name='Image',
        upload_to=banner_folder,
    )
    link = models.URLField()
    view_count = models.PositiveIntegerField(default=0)
    age_from = models.PositiveSmallIntegerField()
    age_to = models.PositiveSmallIntegerField()

    def __str__(self):
        return f"{self.id}. {self.text}"

    def count_increase(self):
        self.view_count += 1
        self.save()

我的序列化器:

# serializers.py

class BannerSerializer(ModelSerializer):
    image = Base64ImageField()
    class Meta:
        model = Banner
        fields = ["id", "text", "description", "image", "link"]
kiayqfof

kiayqfof1#

是的,您可以创建自定义字段:

class AgoField(serializers.Field):
    source_attrs = None

    def run_validation(self, primitive_value):
        return {
            'ago_from': primitive_value['from'],
            'ago_to': primitive_value['to'],
        }

    def get_attribute(self, instance):
        return {'from': instance.ago_from, 'to': instance.ago_to}

    def to_representation(self, value):
        return value
# serializers.py

class BannerSerializer(ModelSerializer):
    ago = AgoField()
    image = Base64ImageField()

    class Meta:
        model = Banner
        fields = ['id', 'ago', 'text', 'description', 'image', 'link']

AgoField仍然需要一些额外的微调,如验证器等。但这是“快乐之路”的基本实现。

相关问题