Django many-to-many model DRF

前端 未结 5 1506
执念已碎
执念已碎 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:23

    Since your Author field is many to many, you will need to override the create method on your serializer.

    def create(self, validated_data):
         author = validated_data.pop(author, None)
         project = Project.objects.save(validated_data)
         if author:
             project.author.add(author)
    

    You will also probably need to set the update method on the serializer, the behavior here can be tricky so make sure you test and make sure the behavior is what you expect.

提交回复
热议问题