Django many-to-many model DRF

前端 未结 5 1615
执念已碎
执念已碎 2021-01-26 04:37

I have the following model structure:

class Project(models.Model):
  author = models.ManyToManyField(Account)
  name = models.CharField(max_length=40, default=\'         


        
5条回答
  •  庸人自扰
    2021-01-26 05:17

    There are two problems here:

    1. Showing nested relationships for M2M field:

    If the field is used to represent a to-many relationship, you should add the many=True flag to the serializer field.

    So you need to add many=True to AccountSerializer:

    author = AccountSerializer(read_only=True, required=False, many=True)
    
    1. A writable nested serializer:

    By default nested serializers are read-only. If you want to support write-operations to a nested serializer field you'll need to create create() and/or update() methods in order to explicitly specify how the child relationships should be saved.

    So if you look at the example and the documentation it seems that you need to implement create or update method.

提交回复
热议问题