DRF 3 - Creating Many-to-Many update/create serializer with though table

后端 未结 2 491
我寻月下人不归
我寻月下人不归 2021-01-31 18:37

I am trying to create a reference app in DRF 3 to demonstrate a nested serializer that can create/update models. The sample code below bombs with \"*create() argument after **

2条回答
  •  情书的邮戳
    2021-01-31 19:20

    Use PrimaryKeyRelatedField shown here:

    http://www.django-rest-framework.org/api-guide/relations/#primarykeyrelatedfield

    class GroupSerializer(serializers.ModelSerializer):
        persons = serializers.PrimaryKeyRelatedField(
            many=True, queryset=Person.objects.all())
    
        class Meta:
            model = Group
            fields = ('name', 'persons')
    

    Create each person first, for example. Person with ID 1, Name = "Bob". Person with ID 2, Name = "Tim". Then post them to the REST Endpoint using their primary keys So:

    # Group create() REST endpoint data to POST
    {'name': 'my group', 'persons': [1, 2]}
    

    Now the people that you had created prior, are part of that Group.

提交回复
热议问题