繁体   English   中英

如何使用 django-rest-framework 将嵌套的 m2m 字段序列化为 self ?

[英]How can I serialize a nested m2m field to self with django-rest-framework?

我有一个User模型,它与自身有一个称为friendsm2m关系,我正在尝试对其进行序列化以查看和更新​​关系中用户的 pk。

模型.py

class User(AbstractBaseUser, PermissionsMixin):
    email = models.EmailField('Email', max_length=254, unique=True)
    name = models.CharField('Full Name', max_length=35, unique=True, null=False, blank=False)

    friends = models.ManyToManyField("User", related_name='user_friends', blank=True)

序列化程序.py

class UserSerializer(serializers.HyperlinkedModelSerializer):
    password = serializers.CharField( 
        write_only=True,
        required=False,
        help_text='Leave empty if no change needed',
        style={'input_type': 'password', 'placeholder': 'Password'}
    ) #  for setting the password
    
    class Meta:
        model = User
        fields = ('pk', 'email', 'name', 'friends', 'password')

    def create(self, validated_data):
        validated_data['password'] = make_password(validated_data.get('password'))
        return super(UserSerializer, self).create(validated_data)

当我转到我的 API 时,我看到以下内容:

{
    "user": {
        "pk": 1,
        "email": "user@gmail.com",
        "name": "User",
        "friends": [
            "http://localhost:8000/user_detailAPI/2/"
        ],
    }
}

但我希望serializer以如下方式在列表中显示每个friend

{
    "user": {
        "pk": 1,
        "email": "user@gmail.com",
        "name": "User",
        "friends": [
            2
        ],
    }
}

另外,如果您能让我知道如何使用POSTPUT请求将对象添加到friends字段,那就太好了,因为我是django-rest-framework新手,我觉得这是一个重要问题。

所以看起来现在没有真正的方法可以做到这一点,但是有一种基本的解决方法:

  1. 从用户模型中删除 m2m 字段。
  2. 创建一个名为FriendRelationship类的辅助表, FriendRelationship包含用户模型的 2 个Foreign Keys
  3. 从助手表中获取好友数据。

这是因为不存在 m2m 关系并且数据很容易提取。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM