2016-07-08 103 views
0

我遇到了DRF和一些序列化程序的奇怪問題。實例化Django REST框架序列化程序時出錯

這裏是我的模型:

class Accommodation(models.Model): 
    created = models.DateTimeField(auto_now_add=True) 
    modified = models.DateTimeField(auto_now=True) 
    product = models.OneToOneField(
     Product, 
     on_delete=models.CASCADE, 
     primary_key=True, 
    ) 
    description = models.TextField(null=True, blank=True, verbose_name=_(u'Description')) 
    shared_accommodation = models.BooleanField(default=False) 
    accommodation_unit_quantity = models.PositiveSmallIntegerField(default=1, 
                   verbose_name=_(u'Number of acommodation units ' 
                       u'for this acommodation')) 
    accommodation_unit_name = models.TextField(null=False, blank=False, verbose_name=_(u'Name for accommodation units ' 
                        u'for this accommodation')) 

    class Meta: 
     verbose_name_plural = _(u'Accommodations') 

    def __unicode__(self): 
     return u'{0} <{1}>'.format(self.product.name, self.product.school) 

class Product(AbstractProduct): 

    name = models.CharField(max_length=50, verbose_name=_(u'Name')) 
    school = models.ForeignKey('school.School') 
    levels = models.ManyToManyField('school.Level',verbose_name=_(u'Level')) 
    age = IntegerRangeField(null=True) 
    gender = models.CharField(choices=GENDER_CHOICES, max_length=1, null=True, blank=True, verbose_name=_(u'Gender')) 
    num_sessions = models.PositiveSmallIntegerField(
     verbose_name=_(u'Number of sessions'), 
     default=1, 
     help_text=_(u"Number of sessions that the product has."), 
    ) 
    school_category = models.ForeignKey(
     'school.Category', 
     blank=True, null=True, 
     verbose_name=_(u'Category') 
    ) 
    addons = models.ManyToManyField('self', 
     verbose_name=_(u'Administrators'), 
     through='AddonInService', 
     symmetrical=False, 
     related_name='addon_can_be_used_in' 
    ) 

    pay_option = models.CharField(choices=PAYMENT_OPTIONS, max_length=1, null=True, blank=True, verbose_name=_(u'Pay_option'), default='U') 
    payment_type = models.CharField(choices=PAYMENT_TYPE, max_length=1, null=True, blank=True, verbose_name=_(u'pay_type')) 
    payment_amount = models.FloatField(verbose_name=_(u'Amount'), default=0.0) 

    objects = ProductManager() 

    class Meta(AbstractProduct.Meta): 
     verbose_name_plural = _(u'Products') 

    def __unicode__(self): 
     return self.name 

正如你所看到的,基本上是一個產品可以是住宿。下面是串行器

class AccommodationSerializer(serializers.ModelSerializer): 
    class Meta: 
     model = Accommodation 
     fields = [ 
      'description', 
      'shared_accommodation', 
      'accommodation_unit_quantity', 
      'accommodation_unit_name', 
     ] 


class ProductAccommodationSerializer(ProductSerializer): 

    accommodation = AccommodationSerializer() 

    class Meta(ProductSerializer.Meta): 
     fields = [ 
      'id', 
      'structure', 
      'upc', 
      'title', 
      'slug', 
      'description', 
      'rating', 
      'date_created', 
      'date_updated', 
      'is_discountable', 
      'name', 
      'age', 
      'gender', 
      'num_sessions', 
      'parent', 
      'product_class', 
      'school', 
      'levels', 
      'school_category', 
      'addons', 
      'color', 
      'price', 
      'all_prices', 
      'variants', 
      'pay_option', 
      'payment_type', 
      'payment_amount', 
      'accommodation', 
     ] 

    def create(self, validated_data): 
     accommodation_data = validated_data.pop('accommodation') 

     levels = [] 
     if 'levels' in validated_data: 
      levels = validated_data.pop('levels') 

     product = Product.objects.create(**validated_data) 
     school_accommodation, created = ProductClass.objects.get_or_create(name='School Accommodation') 
     if created: 
      product.product_class = school_accommodation 
     for lev in levels: 
      product.levels.add(lev) 
     product.save() 

     acc = AccommodationSerializer(product=product, **accommodation_data) 
     acc.save() 
     return product 

class ProductSerializer(serializers.ModelSerializer): 
    age = IntegerRangeField() 
    addons = AddonSerializer(many=True, read_only=True) 
    # Get the price for the Product, using the property in the Model 
    price = serializers.DecimalField(required=False, max_digits=7, 
           decimal_places=2, source='get_price', 
           read_only=True) 
    color = serializers.SerializerMethodField() 

    all_prices = PriceSerializer(source='stockrecords', many=True, 
            required=False) 

    variants = VariantSerializer(many=True, source='children', required=False) 

    class Meta: 
     model = Product 
     fields = [ 
      'id', 
      'structure', 
      'upc', 
      'title', 
      'slug', 
      'description', 
      'rating', 
      'date_created', 
      'date_updated', 
      'is_discountable', 
      'name', 
      'age', 
      'gender', 
      'num_sessions', 
      'parent', 
      'product_class', 
      'school', 
      'levels', 
      'school_category', 
      'addons', 
      'color', 
      'price', 
      'all_prices', 
      'variants', 
      'pay_option', 
      'payment_type', 
      'payment_amount' 
     ] 

執行一個簡單的測試,我嘗試創建一個旅館,我得到以下錯誤:

Traceback (most recent call last): 
File "/home/internetmosquito/git/mvp_opencoast/opencoast_django/opencoast/applications/accommodation/tests/test_accommodations.py", line 165, in test_create_accommodation 
response = self.client.post(url, data, format='json') 
File "/home/internetmosquito/python_envs/opencoast_django/local/lib/python2.7/site-packages/rest_framework/test.py", line 170, in post 
path, data=data, format=format, content_type=content_type, **extra) 
File "/home/internetmosquito/python_envs/opencoast_django/local/lib/python2.7/site-packages/rest_framework/test.py", line 92, in post 
return self.generic('POST', path, data, content_type, **extra) 
File "/home/internetmosquito/python_envs/opencoast_django/local/lib/python2.7/site-packages/django/test/client.py", line 380, in generic 
return self.request(**r) 
File "/home/internetmosquito/python_envs/opencoast_django/local/lib/python2.7/site-packages/rest_framework/test.py", line 159, in request 
return super(APIClient, self).request(**kwargs) 
File "/home/internetmosquito/python_envs/opencoast_django/local/lib/python2.7/site-packages/rest_framework/test.py", line 111, in request 
request = super(APIRequestFactory, self).request(**kwargs) 
File "/home/internetmosquito/python_envs/opencoast_django/local/lib/python2.7/site-packages/django/test/client.py", line 467, in request 
six.reraise(*exc_info) 
File "/home/internetmosquito/python_envs/opencoast_django/local/lib/python2.7/site-packages/django/core/handlers/base.py", line 149, in get_response 
response = self.process_exception_by_middleware(e, request) 
File "/home/internetmosquito/python_envs/opencoast_django/local/lib/python2.7/site-packages/django/core/handlers/base.py", line 147, in get_response 
response = wrapped_callback(request, *callback_args, **callback_kwargs) 
File "/home/internetmosquito/python_envs/opencoast_django/local/lib/python2.7/site-packages/django/views/decorators/csrf.py", line 58, in wrapped_view 
return view_func(*args, **kwargs) 
File "/home/internetmosquito/python_envs/opencoast_django/local/lib/python2.7/site-packages/rest_framework/viewsets.py", line 87, in view 
return self.dispatch(request, *args, **kwargs) 
File "/home/internetmosquito/python_envs/opencoast_django/local/lib/python2.7/site-packages/rest_framework/views.py", line 466, in dispatch 
response = self.handle_exception(exc) 
File "/home/internetmosquito/python_envs/opencoast_django/local/lib/python2.7/site-packages/rest_framework/views.py", line 463, in dispatch 
response = handler(request, *args, **kwargs) 
File "/home/internetmosquito/python_envs/opencoast_django/local/lib/python2.7/site-packages/rest_framework/mixins.py", line 21, in create 
self.perform_create(serializer) 
File "/home/internetmosquito/python_envs/opencoast_django/local/lib/python2.7/site-packages/rest_framework/mixins.py", line 26, in perform_create 
serializer.save() 
File "/home/internetmosquito/python_envs/opencoast_django/local/lib/python2.7/site-packages/rest_framework/serializers.py", line 191, in save 
self.instance = self.create(validated_data) 
File "/home/internetmosquito/git/mvp_opencoast/opencoast_django/opencoast/applications/accommodation/serializers.py", line 77, in create 
acc = AccommodationSerializer(product=product, **accommodation_data) 
File "/home/internetmosquito/python_envs/opencoast_django/local/lib/python2.7/site-packages/rest_framework/serializers.py", line 95, in __init__ 
super(BaseSerializer, self).__init__(**kwargs) 
TypeError: __init__() got an unexpected keyword argument 'product' 

試圖刪除

產品=產品

acc = AccommodationSerializer(product=product, **accommodation_data) 

但是然後我得到相同的錯誤,但與'shared_accommodation'字段而不是產品

我在這裏做錯了什麼?有任何想法嗎?

編輯:添加ProductSerializer,我錯過了一個遺憾

第二個編輯:試圖創建時

class AccommodationSerializer(serializers.ModelSerializer): 
    class Meta: 
     model = Accommodation 
     fields = [ 
      'product', 
      'description', 
      'shared_accommodation', 
      'accommodation_unit_quantity', 
      'accommodation_unit_name', 
     ] 

但後來:正如一些建議,我已經添加了產品領域的AccommodationSerializer一個例子,我得到以下錯誤:

{'accommodation': OrderedDict([('product', [u'This field is required.'])])} 

滑稽的是,如果我的產品添加到測試數據有效載荷(儘管我還沒有創建produc T取代我所說的終點的時間作出住宿,上面dissappears錯誤):

data = { 
     "name": "Hotel Hudson", 
     "slug": "hotel-hudson", 
     "age": {'upper': 99, 'lower': 18}, 
     "school": school1.id, 
     "levels": [school1.level_set.all()[0].id], 
     "accommodation": { 
      "product": 1, 
      "description": "A very nice hotel", 
      "shared_accommodation": False, 
      "accommodation_unit_quantity": 1, 
      "accommodation_unit_name": "Room", 
      "accommodation_units": [ 
       { 
        'name': "Room-1", 
        'max_pax': 1, 
       }, 
       { 
        'name': "Room-2", 
        'max_pax': 3, 
       }, 
      ] 
     }, 
    } 

雖然這是有趣的,這顯然不是我想要的......我不想不必傳遞假設產品ID在調用端點時創建一個Accommodation ...任何指針?

+0

只是'AccommodationSerializer(accommodation_data)',沒有kwargs。如何將'product'放在'accommodation_data'中我將留給回答者。 – Brian

+0

ProductAccommodationSerializer - Meta class ... add'model = Product' – Jerzyk

+0

我真的不喜歡'class Meta(ProductSerializer.Meta)' – Jerzyk

回答

1

使用data字段將是正確的方法,因爲DRF串行器層次結構中的關鍵字不是通用的。如果您爲data指定的字典有效,則可以使用.save()(在致電.is_valid()後)創建模型實例。在創建模型之前,字典當然可以增加更多的屬性。但要小心,序列化程序只使用在序列化程序的Meta.fields字段中指定的屬性。

這裏是關鍵點,爲什麼你的方法畢竟不能工作:AccomodationSerializer.Meta.fields不包括product字段,如果你想創建一個模型,這是必須的。

使用AccommodationSerializerAccommodation模型中讀取或者您想發佈模型的部分結構出於某種原因是很好的。但是如果你想用它來創建一個模型實例,你必須指定所有不爲空或者具有默認值的字段。

除了在此處使用AccommodationSerializer的,你可以只要致電:

Accommodation.objects.create(product=product, **accommodation_data) 

我試圖建立一個最小的例子。希望這可以幫助。

models.py:

class Owner(models.Model): 

    owner_name = models.CharField(max_length=255) 


class Product(models.Model): 

    name = models.CharField(max_length=255) 
    owner = models.OneToOneField(Owner) 

serializer.py

class OwnerSerializer(serializers.ModelSerializer): 

    class Meta: 
     model = Owner 
     fields = [ 
      'owner_name', 
     ] 

class ProductSerializer(serializers.ModelSerializer): 

    owner = OwnerSerializer(read_only=True) 

    class Meta: 
     model = Product 
     fields = [ 
      'owner', 
      'name', 
     ] 


class ProductOwnerSerializer(serializers.ModelSerializer): 

    product = ProductSerializer() 

    class Meta: 
     model = Owner 
     fields = [ 
      'product', 
      'owner_name', 
     ] 

    def create(self, validated_data): 
     product_data = validated_data.pop('product') 
     owner = Owner.objects.create(**validated_data) 
     Product.objects.create(owner=owner, **product_data) 
     return owner 

我也同意Jerzyk的評論,我真的不喜歡Meta(Superclass),似乎是一個反模式我。

+0

感謝您的詳細回覆,我編輯了我的帖子,所以請檢查它。我試過把產品添加到AccommodationSerializer中,但是我得到這個錯誤。我試過你的建議和它的工作原理,但我認爲我通過實例化對象而不是使用AccommodationSerializer來限制自己。如果(因爲這是我的情況)會發生什麼情況我想添加更多字段到該序列化程序,甚至不在模型中(只讀)並返回它們?用你的方法,這是不可能的? – AlejandroVK

+0

將此標記爲正確答案,因爲這指出我正確的方向,現在就開始工作,謝謝@Till – AlejandroVK

+0

事情是,您不需要'AccommodationSerializer'來創建模型。就我理解DRF而言,序列化器並不意味着被用於內聯,以在另一個模型的創建方法中創建不同的模型。使用自定義和相關對象字段進行讀取操作是可以的,但如果您想要創建/更新更復雜的嵌入式結構,則通常需要通過使用模型管理器創建實例來實現您自己的「創建」方法。 –

相關問題