2015-01-22 25 views
9

Có hai kiểu: ProductPicture. Mỗi Product có thể có một số Picture s. Tôi có câu hỏi khi tôi muốn tạo Sản phẩm bằng POST. Làm thế nào để POST một đối tượng lồng nhau có chứa một danh sách ImageField?Cách đăng dữ liệu lồng nhau và danh sách hình ảnh

Mô hình Product là:

class Product(models.Model): 
    product_id = models.AutoField(primary_key=True) 
    product_name = models.CharField(max_length=50) 
    description = models.TextField(blank=True) 

Mô hình Picture là:

class Picture(models.Model): 
    product = models.ForeignKey(Product, related_name='pictures') 
    path = models.ImageField(null=False, upload_to='product_pic') 
    description = models.CharField(max_length=255, null=True, blank=True) 
    main = models.BooleanField() 

Tôi viết serializer.py như sau:

class PictureSerializer(serializers.ModelSerializer): 
    class Meta: 
     model = Picture 
     fields = ('path', 'description', 'main') 

class ProductSerializer(serializers.ModelSerializer): 
    pictures = PictureSerializer(many=True, required=False) 

    class Meta: 
     model = Product 
     fields = ('product_id', 'product_name', 'pictures', 'description') 

Quan điểm cho rằng tôi đang sử dụng là:

class ProductEnum(generics.ListCreateAPIView): 
    queryset = Product.objects.all() 
    serializer_class = ProductSerializer 
    permission_classes = (IsAuthenticated,) 

    def post(self, request, format=None): 
     serializer = ProductSerializer(data=request.DATA, files=request.FILES) 

     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) 

Tôi đăng ký nó trong url như:

url(r'^api/products/$', views.ProductEnum.as_view()), 

Các câu hỏi là:

  • Làm thế nào tôi có thể kiểm tra POST này api như django-rest-framework nói với tôi rằng "Lists hiện không được hỗ trợ trong Nhập HTML "
  • Cách sử dụng JSON để POST một tài nguyên Product với nhiều số Pictures. HOẶC Tôi phải sử dụng trình phân tích cú pháp nhiều phần.
  • Cách viết lệnh cURL?
+1

bạn có quản lý để làm đúng không? – momokjaaaaa

Trả lời

0

Bạn có thể sử dụng manage.py shell. Như sau:

import requests 
r = requests.post("http://localhost:8000/login/url", data={"username": "username", "password": "password"} 
r.content (outputs token) 
token="yourtoken" 
r = requests.post("http://localhost:8000/your/url", data={your POST data in json}, headers={"Authorization": "Token %s" % token}) 
+0

Bạn không trả lời câu hỏi vàng của người đăng bài - Cách sử dụng JSON để POST tài nguyên Sản phẩm có nhiều Hình ảnh. HOẶC Tôi phải sử dụng trình phân tích cú pháp nhiều phần. – momokjaaaaa

0

DRF làm cho việc này trở nên dễ dàng. Bạn đang gần, bạn cần phải ghi đè ProductSerializer.create, một cái gì đó như thế này:

class ProductSerializer(serializers.ModelSerializer): 
    pictures = PictureSerializer(many=True, required=False) 

    class Meta: 
     model = Product 
     fields = ('product_id', 'product_name', 'pictures', 'description') 

    def create(self, validated_data): 
     # Pop this from the validated_data first, since the serializer can't handle it. 
     pictures = validated_data.pop('pictures') 
     product = super().create(validated_data) 
     # Now that we have a product to reference in the FKey, create the pictures. 
     for picture in pictures: 
      # `picture` has been run through the PictureSerialzer, so it's valid. 
      picture['product'] = product 
      Picture.objects.create(**picture) 
     return product 

Có một ví dụ đầy đủ trong các tài liệu, ở đây: http://www.django-rest-framework.org/api-guide/relations/#writable-nested-serializers

Đối với lệnh curl của bạn, nó sẽ là một cái gì đó như:

curl -X POST http://localhost:8000/products/ -H 'ContentType: application/json' -d '{"pictures": [{"description": "first one"}, {"description": "second one"}], "product_name": "foobar"}'

2

bạn phải sử dụng phân tích cú pháp nhiều phần dữ liệu, ngay khi bạn cần phải gửi dữ liệu nhị phân về cơ bản bạn chỉ cần lựa chọn:

  1. suy yếu tiếp cận REST của bạn và làm cho một ngoại lệ -> json không thể giữ dữ liệu nhị phân
  2. mã hóa tất cả các tập tin nhị phân với base64, giữ cách tiếp cận json nhưng bạn cần phải làm de/mã hóa bổ sung cho mọi yêu cầu (không natively hỗ trợ)

Cách tiếp cận có thể thấy thường xuyên là tạo chế độ xem (không nghỉ) để tải lên một/nhiều tệp tạo các đối tượng File hoặc Document (trả về id khi tải lên). Sau đó, bạn có thể sử dụng (các) id này yêu cầu khác, trong trường hợp của bạn tạo/cập nhật Product của bạn.

Nói chung không có cách nào dễ dàng để làm điều đó vì json không hỗ trợ dữ liệu nhị phân.

Các vấn đề liên quan