我需要能夠在api端點上進行一篇文章以保存一個adgroup模型。該模型具有多對多字段。我知道我需要覆蓋create()方法。但是我怎麼被卡住了。傳入的請求數據將具有其他模型(廣告素材)的ID。該ID已經存在於廣告素材表格中。在django休息框架中保存與多對多數據庫的關係的django模型
Django創建另一個名爲adgroup_creative的表來保存此M2M關係。我需要在保存此adgroup對象時填充該表。
class AdGroup(models.Model):
adgroup_name = models.CharField(max_length=200, verbose_name="Name")
creative = models.ManyToManyField(Creative, verbose_name="Creative")
class Creative(models.Model):
creative_name= models.CharField(max_length=200, verbose_name="Name", default=0)
ad_type= models.PositiveIntegerField(max_length=1,verbose_name="Ad Type")
class AdGroupSerializer(serializers.ModelSerializer):
class Meta:
model = AdGroup
fields = ('id','adgroup_name','creative')
class CreativeSerializer(serializers.ModelSerializer):
class Meta:
model = Creative
fields = ('id','creative_name')
class AdGroupViewSet(mixins.CreateModelMixin, mixins.RetrieveModelMixin, mixins.UpdateModelMixin, mixins.ListModelMixin, viewsets.GenericViewSet):
queryset = AdGroup.objects.all().order_by('-id')
serializer_class = AdGroupSerializer
https://codereview.stackexchange.com/questions/46160/django-rest-framework-add-remove-to-a-list
Save a many-to-many model in Django/REST?