Orders在我的 django 应用程序中,我在和之间建立了多对多关系Packages。一个订单可以有多个包裹。我想了解更新和创建方法
模型.py
class Package(models.Model):
prod_name = models.CharField(max_length=255, default=0)
quantity = models.IntegerField(default=0)
unit_price = models.IntegerField(default=0)
class Orders(models.Model):
order_id = models.CharField(max_length=255, default=0)
package = models.ManyToManyField(Package)
is_cod = models.BooleanField(default=False)
序列化程序.py
class PackageSerializer(serializers.ModelSerializer):
class Meta:
model = Package
fields = "__all__"
class OrderSerializer(serializers.ModelSerializer):
package = PackageSerializer(many=True)
class Meta:
model = Orders
fields = "__all__"
视图.py
class OrdersCreateAPIView(generics.CreateAPIView):
permission_classes = (permissions.IsAuthenticated,)
serializer_class = OrderSerializer
def post(self, request):
serializer = OrderSerializer(data=request.data)
if serializer.is_valid():
serializer.save()
return Response(serializer.data, status=status.HTTP_201_CREATED)
return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)
这足以处理相关数据吗?我正在尝试了解ManytoManyDjango 和 DRF 中的关系,所以请解释我是否需要更改模型或视图
更新:
我已经更新了我的序列化程序和视图,以便创建manytomany像这样的相关对象:
class OrderSerializer(serializers.ModelSerializer):
package = PackageSerializer(many=True)
class Meta:
model = Orders
fields = "__all__"
def create(self, validated_data):
package_data = validated_data.pop('package')
pkgs = []
order = Orders.objects.create(**validated_data)
for i in package_data:
try:
p = Package.objects.create(**i)
pkgs.append(p)
except:
pass
order.package.set(pkgs)
return order
但是我仍然不清楚覆盖update. RetrieveUpdateDestroyAPIView另外,上述方法是存储M2M相关对象的正确方法吗?
请帮助更新序列化程序的部分,我知道我必须在序列化程序中传递查询
慕姐8265434
相关分类