简体   繁体   English

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

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

I have a User model that has a m2m relation to itself called friends and I'm trying to serialize it to see and update the pk's of users that are in the relation.我有一个User模型,它与自身有一个称为friendsm2m关系,我正在尝试对其进行序列化以查看和更新​​关系中用户的 pk。

models.py模型.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)

serializers.py序列化程序.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)

When I go to my API I see the following:当我转到我的 API 时,我看到以下内容:

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

but I would like for the serializer to display each friend in a list in a manner like this:但我希望serializer以如下方式在列表中显示每个friend

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

Plus if you could let me know how I would be able to add an object to friends field using POST or PUT request it would be nice because I am new to django-rest-framework and I feel like this is an important problem.另外,如果您能让我知道如何使用POSTPUT请求将对象添加到friends字段,那就太好了,因为我是django-rest-framework新手,我觉得这是一个重要问题。

So looks like there is no real way to do that rigth now but there is a workaround which is bascially:所以看起来现在没有真正的方法可以做到这一点,但是有一种基本的解决方法:

  1. Removing m2m field from user model.从用户模型中删除 m2m 字段。
  2. Creating a helper table called something like FriendRelationship with 2 Foreign Keys to user model.创建一个名为FriendRelationship类的辅助表, FriendRelationship包含用户模型的 2 个Foreign Keys
  3. Getting the friends data from the helper table.从助手表中获取好友数据。

This works as there is no m2m relations present and data is easy to extract.这是因为不存在 m2m 关系并且数据很容易提取。

暂无
暂无

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

相关问题 django rest framework:如何在id之外显示m2m和foreignkey字段? - django rest framework: How can I display m2m and foreignkey fields besides id? Django rest框架嵌套序列化程序不适用于M2M关系 - Django rest framework nested serializer not working for M2M relations Django Rest Framework M2M Through Model字段无法解析 - Django Rest Framework M2M Through Model field not resolving Django Rest Framework可写嵌套序列化程序缺少M2M字段内容 - Django Rest Framework writtable nested serializer is missing m2m field content 如何将OneToOneField序列化为Django-Rest-Framework中的列表? - How can I serialize the OneToOneField to be list in Django-Rest-Framework? 如何在Django Rest Framework中显示我的M2M模型 - how to display my M2M model in Django Rest Framework 如何从django rest框架类基于创建视图的用户个人资料上的M2M字段中添加对象? - How can I add an object to a M2M field on my users profile from django rest frameworks class based create view? django-rest-framework:如何序列化已经包含JSON的字段? - django-rest-framework: How Do I Serialize a Field That Already Contains JSON? Django Rest框架嵌套序列化程序的M2M字段更新方法 - Update method on Django Rest framework nested serializer for M2M fields Django Rest Framework 更新嵌套的 m2m 对象。 有人知道更好的方法吗? - Django Rest Framework updating nested m2m objects. Does anyone know a better way?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM