S
S
stayHARD2015-08-28 15:29:19
Django
stayHARD, 2015-08-28 15:29:19

How to serialize the same object in different ways?

Hello.
The question is, how can one and the same object be serialized differently depending on the contents of another field?
Model:

class Images(models.Model):
  file_name = models.FileField(upload_to = get_file_path_image)
  ordering = models.IntegerField()
  section = models.ForeignKey(Sections, related_name = "images")
  icon = models.FileField(upload_to = get_file_path_icon)
  icon_x = models.CharField(max_length = 500)
  icon_y = models.CharField(max_length = 500)
  text = models.CharField(max_length = 500)
  link_type = models.CharField(max_length = 500)
  link = models.FileField(upload_to = get_file_path_feature)

link_type is of 3 types - Video, Panorama or Link.
Accordingly, the link is written either:
http://ec2**************.eu-west-1.compute.amazona...
or
http://ec****** *********.eu-west-1.compute.amazona...
or
google.com
How to serialize an object differently depending on the type specified in link_type?
I do it through serializers.SerializerMethodField('get_full_path_link')
def get_full_path_link(self, obj):
    if str(obj.link_type) == u'Video':
      return "http://ec***********.eu-west-1.compute.amazonaws.com" + obj.link.url

Answer the question

In order to leave comments, you need to log in

2 answer(s)
E
Eduard_90, 2015-08-28
@Eduard_90

And what is the question? :-)
You have a get_full_path_link method - do whatever you want in it.
Well, or I misunderstood the question.

S
some1else, 2015-12-18
@some1else

If we are talking about django-rest-framework, then:

  1. Write some serializer classes.
  2. In your ViewSet, override the get_serializer method, and return a serializer that is applicable to this particular case.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question