1
我有以下模型和另一個ClientWarehouse。對於一些原因,我已經通過一個名爲RouteInfoDjango Restframework更新manytomany通過表
class Route(models.Model):
user = models.ForeignKey(User)
warehouse = models.ManyToManyField(ClientWarehouse,
verbose_name='Warehouse Location',
through='RouteInfo',
blank=True, null=True)
class RouteInfo(models.Model):
route = models.ForeignKey(Route)
warehouse = models.ForeignKey(ClientWarehouse)
一個通過表中創建ManyToManyField關係我有以下序列化器類writtern
class RouteInfoSerializer(serializers.ModelSerializer):
class Meta:
model = RouteInfo
class RouteSerializer(serializers.ModelSerializer):
warehouse = serializers.PrimaryKeyRelatedField(many=True, read_only=True)
class Meta:
model = Route
並按照視圖集中
class RouteViewSet(viewsets.ModelViewSet):
model = Route
def get_object(self, pk):
try:
return Route.objects.get(pk=pk)
except Route.DoesNotExist:
raise Http404
def create(self, request, format=None):
r = RouteSerializer(data=request.DATA)
if r.is_valid():
r.save()
return Response(r.data, status=status.HTTP_201_CREATED)
return Response(r.errors, status=status.HTTP_400_BAD_REQUEST)
但是在通過持續我發現DRF文檔不支持通過表格對ManytoManyField進行寫操作。
當前當我嘗試通過api調用保存路由時,它不保存客戶端軟件倉庫,即未創建RouteInfo表,但創建的Route對象中沒有客戶端軟件倉庫。
有什麼辦法可以更新通過表即RouteInfo,同時在路由表中創建路由。