我在用djangorestframwork框架为app客户端提供接口,现在遇到个问题如下,IWannaImages表外键IWanna表,现在我通过接口POST提交IWanna数据的时候无法获取客户端POST过来的到关联表IwannaImages的信息
这是我打印的客户端提交的数据validated_data的内容:
{u'platform': u'ios', u'reason': u'\u5b81\u65e5\u8363\u6e7f\u7b54\u7b54\u53d1\u751f\u7684\u53d1\u7ed9\u6211\u7684', u'error_type': u'\u8f6f\u4ef6\u9519\u8bef', u'user_id': 56, u'wanna_type': u'\u7ea0\u9519\u8bef'}
从打印结果来看后台就没接收到客户端传递的images的数据,感觉是serializer这块不对,接口这块该如何处理呢?
models.py
class IWanna(models.Model):
wanna_type = models.CharField(max_length=32, verbose_name=_("I wanna type"))
scene_name = models.CharField(max_length=128, null=True, blank=True, verbose_name=_("scene name"))
city_name = models.CharField(max_length=128, null=True, blank=True, verbose_name=_("city name"))
reason = models.TextField(null=True, blank=True, verbose_name=_("wanna reason"))
user_id = models.IntegerField(verbose_name=_("user id"))
platform = models.CharField(max_length=32, verbose_name=_("platform"))
error_type = models.CharField(max_length=128, null=True, blank=True, verbose_name=_("error type"))
image = models.ImageField(upload_to=wanna_image_upload_to, null=True, blank=True, verbose_name=_("image"))
improve_type = models.CharField(max_length=32, null=True, blank=True, verbose_name=_("improve type"))
class Meta:
app_label = 'people'
verbose_name = _("I Wanna")
verbose_name_plural = _("I Wanna")
def __unicode__(self):
return "{}-{}".format(self.id, self.wanna_type)
class IWannaImages(models.Model):
iwanna = models.ForeignKey("IWanna", related_name="images", verbose_name=_("i wanna type"))
image = models.ImageField(upload_to=wanna_image_upload_to, verbose_name=_("image"))
serializers.py
class IWannaSerializer(serializers.ModelSerializer):
images = serializers.SerializerMethodField()
class Meta:
model = IWanna
fields = (
"id", "wanna_type", "scene_name", "city_name", "reason", "user_id",
"platform", "error_type", "images", "improve_type", "image"
)
depth = 1
def validate(self, attrs):
if attrs["platform"] not in ["ios", "android"]:
raise ValidationError({"platform": "platform not allowed"})
return attrs
def get_images(self, instance):
data = IWannaImageSerializer(instance.images, many=True).data
return data
def create(self, validated_data):
instance = super(IWannaSerializer, self).create(validated_data)
try:
if validated_data["images"]: # traverse images from app
for i in validated_data["images"]:
IWannaImages.objects.create(iwanna=instance, image=i)
except Exception, e:
import logging
logging.warn(e.message)
return instance
class Meta多了depth=1,所以下级的列表被过滤了,你去掉试试!