[英]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
模型,它与自身有一个称为friends
的m2m
关系,我正在尝试对其进行序列化以查看和更新关系中用户的 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.另外,如果您能让我知道如何使用
POST
或PUT
请求将对象添加到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:所以看起来现在没有真正的方法可以做到这一点,但是有一种基本的解决方法:
FriendRelationship
with 2 Foreign Keys
to user model.FriendRelationship
类的辅助表, FriendRelationship
包含用户模型的 2 个Foreign Keys
。 This works as there is no m2m relations present and data is easy to extract.这是因为不存在 m2m 关系并且数据很容易提取。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.