How to add string to a ModelSerializer in Django R

2019-08-25 02:32发布

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)

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__'

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}'

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).

How can I do that?

2条回答
再贱就再见
2楼-- · 2019-08-25 02:49

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)

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

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__'
查看更多
爱情/是我丢掉的垃圾
3楼-- · 2019-08-25 03:01

Try following in your serialiser.py

class ProductSerializer(serializer.ModelSerializer):
     img_url = serializers.SerializerMethodField()
     class Meta:
          model = Product
          fields = '__all__' 
          #fields = ('sku', 'img_url') # This is what i will prefer
     def get_img_url(self, obj):
         storage_location = '/assets/img'
         img_url = f'{storage_location}/{obj.image}'
         return img_url

Good Luck!

查看更多
登录 后发表回答