简体   繁体   中英

request with list of id's for many to many relationship in django rest framework

What is the correct way of implementing the following api with django and django-rest-framework. First the model

Model

def ChatModel(models.Model):
   users = models.ManyToManyField(User, through=ChatUser)

Response

The desired response when getting this model where the many to many relationship is presented with a nested serializer:

[
  {
    "id": 1,
    "title": "gossip",
    "users": [
        {
          "id": 1,
          "name": "George"
        },
        {
          "id": 2,
          "name": "Jerry"
        }  
    ]         
  }
]

The request is the critical part: Have the api receive a list of primary keys and create the user -> chat relationship in the backend.

Request

{
  "title": "gossip",
  "users": [1,2]
}

So how do I allow for such a request to create an object with a many to many relationship.

Edit

I've been trying to implement this using a ChatRequestSerializer class that makes users field something like this

 users = serializers.ListField(child=serializers.PrimaryKeyRelatedField(many=True, queryset=User.objects.all()))

and handle creating the relationships by overriding the create method of the serializer. This doesn't work because it throws the error: 'ManyRelatedManager' object is not iterable

You can use a nested serializer:

class NestedUserSerializer(serializers.ModelSerializer):
    class Meta(object):
        model = models.User
        fields = ('id', 'name')
        readonly_fields = ('name',)


class ParentSerializer(serializers.ModelSerializer):
    users = NestedUserSerializer(many=True)

    class Meta(object):
        model = models.Parent
        fields = ('id', 'title', 'users')

    def create(self, validated_data):
        user_ids = {u['id'] for u in validated_data.pop('users', [])}
        parent = super(ParentSerializer, self).create(validated_data)
        # create users here
        return parent

The code is not tested. But I hope it will demonstrate my idea.

Please note that input should look like this:

{
    "title": "gossip",
    "users": [{"id": 1}, {"id": 2}]
}

Also you can check this answer: django rest framework nested fields with multiple models

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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