简体   繁体   中英

How to serialize Filefield or Imagefield data into json data in python django

i'm actually an amateur python programmer and am trying to use the django framework for an android app backend. everything is okay but my problem is actually how to pass the image in the Filefield to JSON. i have tried using SerializerMethodField as described in the rest framework documentation but didn't work. sorry if this question is off track but i seriously need help.

This is from my serializer class

class DealSerializer(serializers.ModelSerializer):
class Meta:
    model = Deal
    image = serializers.SerializerMethodField()
    fields = [
        'title',
        'description',
        'image'
    ]

    def get_image(obj):
        return obj.image.url

and this is my view

class DealList(APIView):

   def get(self, request):
      deals= Deal.objects.all()
      serializer = DealSerializer(deals, many=True)
      return Response(serializer)

Just do something like this:

class PhotoSerializer(serializers.ModelSerializer):

    class Meta:
        model = Photo
        read_only_fields = ('created_on', 'updated_on')

class PhotoViewSet(CreateListModelMixin, viewsets.ModelViewSet):
    serializer_class = PhotoSerializer
    queryset = Photo.objects.all()


def ref_directory_path(instance, filename):
    # file will be uploaded to MEDIA_ROOT/ref/<id>/
    return 'ref/{0}/{1}'.format(instance.ref.id, filename)

class Photo(models.Model):

    image = models.ImageField(upload_to=estates_directory_path)
    caption = models.CharField(max_length=50, blank=True)
    description = models.TextField(blank=True)
    ref_model = models.ForeignKey(MyModel, on_delete=models.CASCADE,
                           related_name="pictures")

    def __str__(self):
        return self.caption

And in the referenced model serializer:

class MyModelSerializer(serializers.HyperlinkedModelSerializer):

    url_apprise = serializers.HyperlinkedIdentityField(
        view_name='estate-assess')
    location_info = LocationInfoSerializer(many=True, read_only=True)
    photos = PhotoSerializer(many=True, read_only=True)

    class Meta:
        model = Estate
        read_only_fields = ('created_on', 'updated_on')

Okay.. i've managed to fix it and can now serialize the filefield and all other fields into json data. this is the code. From my serializer.py.

class DealSerializer(serializers.ModelSerializer):
  class Meta:
    model = Deal
    fields = ('title', 'description', 'image')

From my views.py file.

class DealViewSet(viewsets.ModelViewSet):
queryset = Deal.objects.all()
serializer_class = DealSerializer

the trick happened in the urls.py. i used "routers" which is a class that comes with the rest_framework. it creates a custom view for you in the background and all you do is add a url that leads to that view. so you do something like this

router = routers.DefaultRouter()
router.register('deals', DealViewSet, 'deals')

urlpatterns = [
   url(r'^api/', include(router.urls)),]

the router takes 3 parameters, the 1st one is the prefix for the url(so in my case 'api/deals'), the 2nd one is the name of the model class in the views.py and the last one is just a name for your view.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM