Добрый день. Рукурсивно стерилизую иерархические данные.
Можно ли в serializers не выводить поле вовсе, а не выводить пустое?
class HierarchicalTag(MPTTModel, TagBase):
name = models.CharField(max_length=50, unique=True)
parent = TreeForeignKey('self', null=True, blank=True, related_name='children', db_index=True, on_delete=models.CASCADE)
def __str__(self):
return self.name
class MPTTMeta:
order_insertion_by = ['name']
def __unicode__(self):
return self.name
view
class TagsList(generics.ListAPIView):
serializer_class = ReadHierarchicalTagSerializer
permission_classes = [permissions.IsAuthenticatedOrReadOnly]
def get_queryset(self):
return HierarchicalTag.objects.root_node(tree_id=1).get_ancestors(include_self=True)
serializers
class ReadHierarchicalTagSerializer(serializers.ModelSerializer):
user = serializers.SerializerMethodField()
children = serializers.ListField(child=RecursiveField(), source='get_children', read_only=True)
class Meta:
model = HierarchicalTag
fields = ['id', 'name', 'children', 'user']
def get_user(self, model):
if TaggedContentItem.objects.filter(tag_id=model.id).exists():
return [o.content_object.user.username for o in TaggedContentItem.objects.filter(tag_id=model.id)]
json_data
{
"id": 36,
"name": "MS Project",
"children": [],
"user": null
}