添加与JSON响应的多对多关系的所有id-s的列表

时间:2022-11-25 12:07:55

I want to add all the id-s of a many-to-many-relationship to my serialized JSON response.

我想将多对多关系的所有id添加到我的序列化JSON响应中。

class TestField(serializers.Field):
   def to_native(self, value):
       list = []
       for boss in value.all():
           list.append(value).append(';')
       return list

class EmployeeSerializer(serializers.HyperlinkedModelSerializer):
   test = TestField('test')

   class Meta:
       model = Employee
       fields = ('id', 'test', 'bosses')
       depth = 1

So what I want to achieve is: I want to have all of the bosses of the Employee in the response, along with an additional a list of all their id-s, separated by ;.

所以我想要实现的是:我希望在响应中拥有Employee的所有老板,以及另外一个所有id-s的列表,以...分隔。

I've tried using the custom file I created, but for some reason I keep getting the following error.

我已经尝试使用我创建的自定义文件,但由于某种原因,我不断收到以下错误。

AttributeError at /employees/

/ employees /的AttributeError

'Employee' object has no attribute 'test'

'Employee'对象没有属性'test'

What does this error mean and how can I fix my code to give me a list of the id-s?

这个错误是什么意思,我如何修复我的代码给我一个id-s列表?

1 个解决方案

#1


1  

Django REST framework provides a PrimaryKeyRelatedField that allows you to serialize a relation as a list of primary keys, which sounds exactly like what you are looking for.

Django REST框架提供了一个PrimaryKeyRelatedField,它允许您将关系序列化为主键列表,这听起来与您正在寻找的完全一样。

class EmployeeSerializer(serializers.HyperlinkedModelSerializer):
    test = serializers.PrimaryKeyRelatedField(
        read_only=True,
        many=True,
        source='relation'
    )

    class Meta:
        model = Employee
        fields = ('id', 'test', 'bosses')
        depth = 1

This will serialize the list of primary keys as test. The primary keys are the same as the primary keys of the objects returned by employee.relation.all() (because the source is set to "relation").

这将序列化主键列表作为测试。主键与employee.relation.all()返回的对象的主键相同(因为源设置为“relation”)。

#1


1  

Django REST framework provides a PrimaryKeyRelatedField that allows you to serialize a relation as a list of primary keys, which sounds exactly like what you are looking for.

Django REST框架提供了一个PrimaryKeyRelatedField,它允许您将关系序列化为主键列表,这听起来与您正在寻找的完全一样。

class EmployeeSerializer(serializers.HyperlinkedModelSerializer):
    test = serializers.PrimaryKeyRelatedField(
        read_only=True,
        many=True,
        source='relation'
    )

    class Meta:
        model = Employee
        fields = ('id', 'test', 'bosses')
        depth = 1

This will serialize the list of primary keys as test. The primary keys are the same as the primary keys of the objects returned by employee.relation.all() (because the source is set to "relation").

这将序列化主键列表作为测试。主键与employee.relation.all()返回的对象的主键相同(因为源设置为“relation”)。