如何在Django REST中将字符串添加到ModelSerializer [英] How to add string to a ModelSerializer in Django REST

查看:82
本文介绍了如何在Django REST中将字符串添加到ModelSerializer的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在我的数据库中,我存储了特定图像的文件名。假设这是来自django的 models.py

In my database, I store the file name of a particular image for an item. Let's say this is the model in models.py

from django.db import models

class Product(models.Model):
    sku = models.CharField(validators=[isalphanumeric], max_length=20, null=False, blank=False)
    image = models.CharField(max_length=20, blank=False, null=False)

我有一个像这样定义的序列化器,在 serializers.py

and then I have a serializer defined like so in serializers.py

from rest_framework import serializers
from app.models import Product

class ProductSerializer(serializer.ModelSerializer):
    class Meta:
        model = Product
        fields = '__all__'

我想要的是能够将字符串添加到<$ c $的图像中c> Product 使其成为表示相对链接的字符串,例如:

what I want is to be able to add a string to the image of a Product that makes it into a string representing the relative link, something like:

storage_location = '/assets/img'
img_url = f'{storage_location}/{image}'

之所以要这样做,是因为我想灵活使用url,而不是将文件名设置为文件位置,然后每次我都必须更新数据库更改我排列图像的方式(我仍然不确定如何存储它们)。

The reason why I want to do this is because I want to be flexible with the urls rather than having the file name be a "file location" and then having to update the database each time I change how I arrange my images (I'm still not sure how to store them).

我该怎么做?

推荐答案

首先,您可以使用模型的 ImageField 为此:

First of all you can use model's ImageField for this:

class Product(models.Model):
    sku = models.CharField(validators=[isalphanumeric], max_length=20, null=False, blank=False)
    image = models.ImageField(max_length=20, blank=False)

这将自动添加 MEDIA_URL 设置为获取值时的值。

This will automatically add MEDIA_URL setting to the value when you fetch value.

如果您想使用 CharField ,则可以使用 SerializerMethodField

In case you want to use CharField you can do what you need on serializer level using SerializerMethodField:

class ProductSerializer(serializer.ModelSerializer):
    image = serializers.SerializerMethodField()

    def get_image(self, obj):
        storage_location = '/assets/img'
        img_url = f'{storage_location}/{obj.image}'
        return img_url

    class Meta:
        model = Product
        fields = '__all__'

这篇关于如何在Django REST中将字符串添加到ModelSerializer的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆