Пользовательское поле сериализатора Django Rest Framework не запускает `to_representation ()`, если значение равно нулю

Если вы используете версию post r2014b, вы можете использовать недокументированные функции, чтобы изменить цвет каждой строки и главы:

figure
[x,y] = meshgrid(-2:.5:2,-1:.5:1);
z = x .* exp(-x.^2 - y.^2);
[u,v,w] = surfnorm(x,y,z);
h=quiver3(x,y,z,u,v,w); 

s = size(x);
nPoints = s(1)*s(2);
% create a colour map
cmap = parula(nPoints);
% x2 because each point has 2 points, a start and an end.
cd = uint8(repmat([255 0 0 255]', 1, nPoints*2));
count = 0;
% we need to assign a colour per point
for ii=1:nPoints
  % and we need to assign a colour to the start and end of the 
  %   line.
  for jj=1:2
    count = count + 1;
    cd(1:3,count) = uint8(255*cmap(ii,:)');
  end
end
% set the colour binding method and the colour data of the tail
set(h.Tail, 'ColorBinding','interpolated', 'ColorData',cd)

% create a color matrix for the heads
cd = uint8(repmat([255 0 0 255]', 1, nPoints*3));
count = 0;
% we need to assign a colour per point
for ii=1:nPoints
  % and we need to assign a colour to the all the points 
  %   at the head of the arrow
  for jj=1:3
    count = count + 1;
    cd(1:3,count) = uint8(255*cmap(ii,:)');
  end
end
% set the colour binding method and the colour data of the head
set(h.Head, 'ColorBinding','interpolated', 'ColorData',cd)

Примечание: я не сделал ничего умного с величиной и просто изменил цвет каждого колчана, основанный на порядке в исходной матрице, но вы должны иметь возможность получить представление о том, как использовать эту «функцию»

1
задан trubliphone 18 January 2019 в 16:00
поделиться

1 ответ

Насколько я могу понять из реализации , метод to_representation не вызывается, если значение равно Нет . Поэтому, чтобы избежать этой проблемы, я думаю, что вы можете использовать SerializerMethodField . Вы можете использовать это так:

class BookSerializer(serializers.ModelSerializer):
  rating = serailizer.SerializerMethodField()

  class Meta:
    model = Book
    fields = ("title", "rating",)

  def get_rating(self, obj):
      if obj.rating == None:
         return "Something"
      return obj.rating
0
ответ дан ruddra 18 January 2019 в 16:00
поделиться
Другие вопросы по тегам:

Похожие вопросы: