2016-02-21 41 views
0

我正在Django rest-framework中的ModelSerializers上工作。**************在Django-Rest框架中的AssertionError

models.py

from __future__ import unicode_literals 
from django.db import models 
from django.contrib.postgres.fields import ArrayField 
from django.contrib.postgres.fields import HStoreField 
from django.contrib.postgres.validators import KeysValidator 

    class Component(models.Model): 
     component_name = models.CharField(max_length=50) 
     allowed_extensions = ArrayField(models.CharField(max_length=50)) 

     def __str__(self): 
      return self.component_name 

    class Image_Type(models.Model): 
     image_name = models.CharField(max_length=30) 
     def __str__(self): 
      return self.image_name 
    class Image_Component(models.Model): 
     component_name = models.ForeignKey('Component') 
     image_name = models.ForeignKey('Image_Type') 
    class Image_Meta(models.Model): 
     image_component = models.ForeignKey('Image_Component',on_delete=models.CASCADE,) 
     component_id = models.IntegerField() 
     image_count = models.IntegerField(default=0) 
     version = models.CharField(max_length=10) 

    class Image(models.Model): 
     image_meta = models.ForeignKey('Image_Meta',on_delete=models.CASCADE,) 
     image_path = models.URLField(max_length=200) 
     order = models.IntegerField() 
     version = models.CharField(max_length=10) 


    class Feature(models.Model): 
     image_component = models.ForeignKey('Image_Component',on_delete=models.CASCADE,) 
     feature_value = HStoreField() 
     def save(self,*args,**kwargs): 
      if Feature.objects.filter(feature_value__has_keys=['size', 'quality' , 'format']): 
       super(Feature, self).save(*args, **kwargs) 
      else: 
       print("Incorrect key entered") 

serializers.py

from rest_framework import serializers 
from models import Component , Image_Type , Image_Component , Image , Feature , Image_Meta 
from django.contrib.postgres.fields import ArrayField 
from django.contrib.postgres.fields import HStoreField 


class ComponentSerializer(serializers.ModelSerializer): 
    class Meta: 
     model = Component 
     field = {'component_name','allowed_extensions'} 


class Image_TypeSerializer(serializers.ModelSerializer): 
    class Meta: 
     model = Image_Type 
     field = {'image_name'} 



class Image_ComponentSerializer(serializers.ModelSerializer): 
    component_name = ComponentSerializer() 
    image_name = Image_TypeSerializer() 
    class Meta: 
     model = Image_Component 
     field = {'component_name','image_name'} 

    def create(self, validated_data): 
     component_data = validated_data.pop('component_name') 
     image_data = validated_data.pop('image_name') 
     image_component = Image_Component.objects.create(**validated_data) 

     for component_data in component_data: 
      Component.objects.create(image_component=image_component, **component_data) 

     for image_data in image_data: 
      Image_Type.objects.create(image_component=image_component, **image_data) 

     return image_component 

class Image_MetaSerializer(serializers.ModelSerializer): 
    image_component = Image_ComponentSerializer() 
    class Meta: 
     model = Image_Meta 
     field = {'image_component','component_id' , 'image_count', 'version'} 

class ImageSerializer(serializers.ModelSerializer): 
    image_meta = Image_MetaSerializer() 
    class Meta: 
     model = Image_Meta 
     field = {'image_meta' , 'image_path' , 'order' , 'version'} 

class FeatureSerializer(serializers.ModelSerializer): 
    image_component = Image_ComponentSerializer() 
    class Meta: 
     model = Feature 
     field = {'image_component' , 'feature_value'} 

urls.py

from django.conf.urls import patterns , include , url 
from rest_framework.urlpatterns import format_suffix_patterns 
from imagedata import views 

urlpatterns = patterns('', 
    url(r'^api/component$',views.Component.as_view()), 
    url(r'^api/image_type$',views.Image_Type.as_view()), 
    url(r'^api/image_meta$',views.Image_Meta.as_view()), 
    url(r'^api/image_component$',views.Image_Component.as_view()), 
    url(r'^api/image$',views.Image.as_view()), 
    url(r'^api/feature$',views.Feature.as_view()), 
) 

urlpatterns = format_suffix_patterns(urlpatterns) 

它工作正常的組件image_type模型,即如果我嘗試更新這些表,我可以爲兩者做。但對於image_component模型每當我試圖更新表我得到的錯誤:

AssertionError at /imagedata/api/image_component 
The `.create()` method does not support writable nestedfields by default. 
Write an explicit `.create()` method for serializer `imagedata.serializers.Image_ComponentSerializer`, or set `read_only=True` on nested serializer fields. 
Request Method: POST 
Request URL: http://127.0.0.1:8000/imagedata/api/image_component 
Django Version: 1.9 
Exception Type: AssertionError 
Exception Value:  
The `.create()` method does not support writable nestedfields by default. 
Write an explicit `.create()` method for serializer `imagedata.serializers.Image_ComponentSerializer`, or set `read_only=True` on nested serializer fields. 
Exception Location: /Library/Python/2.7/site-packages/rest_framework/serializers.py in raise_errors_on_nested_writes, line 724 
Python Executable: /usr/bin/python 
Python Version: 2.7.10 

http://127.0.0.1:8000/imagedata/api/image_component的頁面看起來是這樣的:enter image description here

我可能是完全錯誤的,但我認爲該文本字段應要求從component_nameimage_type的值中選擇,它們分別存在於組件和Image_Type表中,但它們不是。我做錯了什麼?以及如何糾正?

Django-Admin也沒有問題。它工作得很好。

回答

1

作爲第一件事,我想說我很確定你得到的錯誤是在Image_ComponentSerializer上添加.create方法之前。

由於Image_Component是基於2個的外鍵,如果你想在API中與他們兩個的選擇字段,只是改變你的序列化到這個(刪除.create方法因爲不需要):

class Image_ComponentSerializer(serializers.ModelSerializer): 
    class Meta: 
     model = Image_Component 

所以沒有自定義序列化器,但是這會影響Image_Component對象的表示,它將顯示FK字段的ID。要改變這種行爲,我重寫.to_representation方法是這樣的:

def to_representation(self, obj): 
    ret = {'component_name': ComponentSerializer(instance=obj.component_name).data, 
      'image_name': ImageTypeSerializer(instance=obj.image_name).data} 
    return ret 

因此,輸入將FK的ID和輸出將根據每個字段的自定義序列。

+0

它的工作.... Thanx :) –

+0

我被困在另一個問題..問題是在**功能**表** ** feature_value **字段中使用的Hstore字段。在嘗試在Django-Rest Framework頁面中保存特徵值時,存儲的特徵值爲空。你能幫我弄清楚什麼嗎? –