在 django rest 序列化程序中使用 django mptt 包时如何获取父节点名称?
How to get parent node name while using django mptt package in django rest serializers?
我只能通过此代码获取父节点 ID,但我需要父节点名称。是否可以获取父节点名称?
class Department(MPTTModel,NameStatusModelMixin):
desc = models.TextField(blank=True, null=True, default=None)
slug = models.SlugField(max_length=100, blank=True)
parent = TreeForeignKey('self', on_delete=models.CASCADE, null=True, blank=True, related_name='children')
related_positions = models.ManyToManyField('Position', related_name='departments')
class MPTTMeta:
order_insertion_by = ['id']
def __str__(self):
return self.name
class DepartmentDetailSerializer(ModelSerializer):
class Meta:
model = Department
fields = ('id', 'name', 'status', 'slug', 'desc', 'parent')
最简单的方法是:
class ParentSerializer(ModelSerializer):
class Meta:
model = Department
fields = ('name')
class DepartmentDetailSerializer(ModelSerializer):
parent = ParentSerializer()
class Meta:
model = Department
fields = ('id', 'name', 'status', 'slug', 'desc', 'parent')
您还可以考虑使用 SerializerMethodField or a recursive/self-referential serializer,具体取决于您希望最终数据看起来像的确切 needs/what...
我只能通过此代码获取父节点 ID,但我需要父节点名称。是否可以获取父节点名称?
class Department(MPTTModel,NameStatusModelMixin):
desc = models.TextField(blank=True, null=True, default=None)
slug = models.SlugField(max_length=100, blank=True)
parent = TreeForeignKey('self', on_delete=models.CASCADE, null=True, blank=True, related_name='children')
related_positions = models.ManyToManyField('Position', related_name='departments')
class MPTTMeta:
order_insertion_by = ['id']
def __str__(self):
return self.name
class DepartmentDetailSerializer(ModelSerializer):
class Meta:
model = Department
fields = ('id', 'name', 'status', 'slug', 'desc', 'parent')
最简单的方法是:
class ParentSerializer(ModelSerializer):
class Meta:
model = Department
fields = ('name')
class DepartmentDetailSerializer(ModelSerializer):
parent = ParentSerializer()
class Meta:
model = Department
fields = ('id', 'name', 'status', 'slug', 'desc', 'parent')
您还可以考虑使用 SerializerMethodField or a recursive/self-referential serializer,具体取决于您希望最终数据看起来像的确切 needs/what...