1 回答
TA贡献1813条经验 获得超2个赞
工作代码库
#serializers.py
class PackageSerializer(serializers.ModelSerializer):
id = serializers.IntegerField()
class Meta:
model = Package
fields = "__all__"
class OrderSerializer(serializers.ModelSerializer):
package = PackageSerializer(many=True)
def get_or_create_packages(self, packages):
package_ids = []
for package in packages:
package_instance, created = Package.objects.get_or_create(pk=package.get('id'), defaults=package)
package_ids.append(package_instance.pk)
return package_ids
def create_or_update_packages(self, packages):
package_ids = []
for package in packages:
package_instance, created = Package.objects.update_or_create(pk=package.get('id'), defaults=package)
package_ids.append(package_instance.pk)
return package_ids
def create(self, validated_data):
package = validated_data.pop('package', [])
order = Orders.objects.create(**validated_data)
order.package.set(self.get_or_create_packages(package))
return order
def update(self, instance, validated_data):
package = validated_data.pop('package', [])
instance.package.set(self.create_or_update_packages(package))
fields = ['order_id', 'is_cod']
for field in fields:
try:
setattr(instance, field, validated_data[field])
except KeyError: # validated_data may not contain all fields during HTTP PATCH
pass
instance.save()
return instance
class Meta:
model = Orders
fields = "__all__"
#views.py
class OrderViewSet(viewsets.ModelViewSet):
serializer_class = OrderSerializer
queryset = Orders.objects.all()
DefaultRouter在as的帮助下注册此视图,
from rest_framework.routers import DefaultRouter
router = DefaultRouter()
router.register(r'order', OrderViewSet, basename='order')
urlpatterns = [
] + router.urls
因此,您将获得该表中描述的基本 CRUD 端点(参见DefaultRouter
参考文献)。
让您的订单列表端点成为/foo-bar/order/
HTTP POST 来
/foo-bar/order/
创建一个新实例HTTP PUT 或 HTTP PATCH
/foo-bar/order/<ORDER_PK>/
以更新内容
笔记
在这种情况下,id
如果您希望将现有的包关系映射到Order
更新-1
您可以像这样连接视图
urlpatterns = [
path('foo/order/', OrderViewSet.as_view({'post': 'create'})), # create new Order instance
path('foo/order/<int:pk>/', OrderViewSet.as_view({'patch': 'partial_update'})), # update Order instance
]
注意:这仅支持HTTP POST和HTTP PATCH
添加回答
举报