我想发一个批量帖子。 问题是每个项目都需要一个图像(或者甚至是一些图像)。 是否可以通过批量请求执行此操作?
模特:
class CollageItem(models.Model):
url = models.URLField(null = True)
image = models.FileField(upload_to = 'i')
thumbnail = models.FileField(upload_to = 't')
和TastyPie对象:
class CollageItemResource(ModelResource):
image = fields.FileField(attribute = 'image', null = True, blank = true)
thumbnail = fields.FileField(attribute = 'thumbnail', null = True, blank = true)
class Meta:
queryset = CollageItem.objects.all(
resource_name = "collage_item"
我可以使用批量请求发布多张图片,还是应该恢复为个别帖子?
答案 0 :(得分:0)
答案 1 :(得分:0)
我选择了自定义序列化器:
class FormPostSerializer(Serializer):
formats = ['form']
content_types = {
'form': 'multipart/form-data',
}
def from_form(self, content):
try:
dict = cgi.parse_multipart(StringIO(content), self.form_boundary)
except Exception, e:
raise e
for key, value in dict.iteritems():
dict[key] = value[0] if len(value) > 0 else None
return dict
需要发布多个文件的所有资源的基类:
class FormResource(ModelResource):
class Meta:
serializer = FormPostSerializer()
def dispatch(self, request_type, request, **kwargs):
cth = request.META.get('CONTENT_TYPE') or \
request.META.get('Content-type') or \
self._meta.serializer.content_types['json']
self.Meta.serializer.form_boundary = self.parse_content_type_header(cth)
return super(FormResource, self).dispatch(request_type, request, **kwargs)
def parse_content_type_header(self, content_type_header):
parts = cgi.parse_header(content_type_header)
rv = {}
for p in parts:
if isinstance(p, dict):
rv = dict(rv.items() + p.items())
return rv
当然,序列化程序需要一些额外的处理(例如UTF8字段)我省略了答案。