简体   繁体   English

如何在Django Rest Framework中序列化多个到多个字段

[英]How to serialize in Django Rest Framework with a many to many field

I have a model called UserProfile which is a OneToOneField to the default User model. 我有一个名为UserProfile的模型,它是默认User模型的OneToOneField I have a Post model which has User as ManyToManyField . 我有一个Post模型,其中UserManyToManyField I am unable to write a serializer for Post which includes User in responses. 我无法为Post编写一个序列化程序,其中包含User的响应。

My UserProfile model: 我的UserProfile模型:

class UserProfile(models.Model):
    user = models.OneToOneField(User)
    name = models.CharField(max_length=255, null=True)
    profile_picture = models.CharField(max_length=1000, null=True)

My Post model: 我的Post模型:

class Post(models.Model):
    text = models.TextField(null=True)
    title = models.CharField(max_length=255, null=True)
    created_at = models.DateTimeField(auto_now_add=True)
    updated_at = models.DateTimeField(auto_now=True)

    user = models.ManyToManyField(User)

My Post serializer: 我的Post序列化器:

class PostSerializer(serializers.ModelSerializer):
    users = UserProfileSerializer(source='user.userprofile', many=True)

    class Meta:
        model = Post
        fields = ('id', 'text', 'title', 'users')

With above serializer I am getting the following error: 使用上面的序列化程序,我收到以下错误:

Got AttributeError when attempting to get a value for field `users` on serializer `WorkSerializer`.
The serializer field might be named incorrectly and not match any attribute or key on the `Work` instance.
Original exception text was: 'ManyRelatedManager' object has no attribute 'userprofile'.

EDIT : I created another serializer UserSerializerForPost which is used in PostSerializer : 编辑 :我创建了另一个在PostSerializer使用的序列化UserSerializerForPost PostSerializer

class UserSerializerForPost(serializers.ModelSerializer):
    user = UserProfileSerializer(source='userprofile')

    class Meta:
        model = User
        fields = ('user',)


class PostSerializer(serializers.ModelSerializer):
    users = UserSerializerForPost(source='user', many=True)

    class Meta:
        model = Post
        fields = ('id', 'text', 'title', 'users')

Though this works, but I am getting UserProfile response in a dictionary of user as users list: 虽然这个工作,但我得到UserProfile中的字典响应userusers列表:

"users": [
  {
    "user": {
      "id": 2,
      ...
  },
  {
    "user": {
      "id": 4,
      ...
    }
  }
]

But I want: 但我想要:

"users": [
  {
    "id": 2,
    ...
  },
  {
    "id": 4,
    ...
    }
  }
],

Following solution worked for me and it did not even require creating UserSerializerForPost : 以下解决方案为我工作,它甚至不需要创建UserSerializerForPost

class PostSerializer(serializers.ModelSerializer):
    users = serializers.SerializerMethodField()

    class Meta:
        model = Post
        fields = ('id', 'text', 'title', 'users')

    def get_users(self, obj):
        response = []
        for _user in obj.user.all():
            user_profile = UserProfileSerializer(
                _user.userprofile,
                context={'request': self.context['request']})
            response.append(user_profile.data)
        return response

EDIT : Okay I found a even better approach than the above. 编辑 :好的,我找到了比上面更好的方法。 First add a get_user_profiles to Post : 首先将一个get_user_profiles添加到Post

class Post(models.Model):
    text = models.TextField(null=True)
    title = models.CharField(max_length=255, null=True)
    created_at = models.DateTimeField(auto_now_add=True)
    updated_at = models.DateTimeField(auto_now=True)

    user = models.ManyToManyField(User)

    def get_user_profiles(self):
        return UserProfile.objects.filter(user__post=self)

Then I updated my PostSerializer with: 然后我更新了我的PostSerializer:

class PostSerializer(serializers.ModelSerializer):
    users = UserProfileSerializer(source='get_user_profiles', many=True)

    class Meta:
        model = Post
        fields = ('id', 'text', 'title', 'users')

This is way too cleaner version that earlier one. 这是比早期版本更清晰的版本。

暂无
暂无

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

相关问题 Django.rest_framework:如何序列化一对多? - Django.rest_framework: How to serialize one to many to many? Django Rest Framework中如何序列化三个多对多关系的模型 - How to serialize three models with many to many relationships in Django Rest Framework Django Rest Framework过滤多对多字段 - Django Rest Framework filtering a many to many field Django rest 框架序列化多对多字段 - Django rest framework serializing many to many field 使用Django REST用一个额外的字段序列化多对多关系 - Serialize a many-to-many relationship with a single extra field with Django REST 如何使用 Django Rest 框架中的中间表序列化自递归多对多 model? - How to serialize a self recursive many-to-many model using an intermediate table in Django Rest Framework? 当在请求中的某个字段内建模数据时,如何使用具有多对多字段和外键的 Django Rest Framework 模型序列化创建? - How to serialize creation with Django Rest Framework models with many-to-many field and foreign-key, when models data inside some field in request? Django Rest框架在序列化多个对象时添加更多数据 - Django rest framework add more data when serialize many object 如何在 Django REST Framework 序列化程序中检索具有向后关系查找的多对多字段? - How to retrieve a many-to-many field with backward relationships lookup in Django REST Framework serializer? 如何验证 Object 与特定参与者(多对多字段)在 Django Rest 框架中是否存在 - How To Validate If A Conversation Object With Particular Partcipants (Many to Many Field) Exist or nott in Django Rest Framework?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM