2016-11-15 84 views
1

在我的API的原始數據表明,在作出POST請求這種結構的POST請求。如何讓Django的REST框架與數組屬性的對象

{ 
    "empID": "", 
    "fullname": "", 
    "contactnumber": [] 
} 

,並在這裏的API列表是一些例子結構:

{ 
    "empID": "DJS1003", 
    "fullname": "Doe, John Smith", 
    "contactnumber": [ 
     { 
      "contactnumber": "123456789" 
     }, 
     { 
      "contactnumber": "321456879" 
     } 
    ] 
} 

現在,讓一個POST請求時,我的目標數據是這樣的:

contactnumber : Array[2] 
    0:"444-1234" 
    1:"0911-124-7854" 
fullname:"John Doe" 
empID:"1001" 

而我得到的說,這個錯誤:

contactnumber:[{non_field_errors:[「無效的數據。預期 字典,卻得到了海峽。「]},...]

UPDATE

這是我model.py

class Employee(models.Model): 
    empID = models.CharField(primary_key=True, max_length= 50, null=False) 
    fullname = models.CharField(max_length=50) 

class ContactNumber(models.Model): 
    empID = models.ForeignKey(Employee, related_name="contacts", to_field='empID', on_delete = models.CASCADE) 
    contactnumber = models.CharField(max_length=13) 

這是我serialzer.py

class ContactsSerializer(serializers.ModelSerializer): 
     class Meta: 
      model = ContactNumber 
      fields = (
        'empID_id', 
        'contactnumber', 
      ) 

class EmployeeListSerializer(serializers.ModelSerializer): 
     contacts = ContactsSerializer(many=True) 

     class Meta: 
      model = Employee 
      fields = (
        'empID', 
        'fullname', 
      ) 
+0

您可以發佈您的視圖集中和串行代碼? – Dap

+0

@Dap我剛剛更新了我的帖子 –

回答

2

那麼,我認爲這個錯誤是足夠明確的,

DRF預計的是:

{ 
    "empID": "DJS1003", 
    "fullname": "Doe, John Smith", 
    "contactnumber": [ 
     { 
      "contactnumber": "123456789" 
     }, 
     { 
      "contactnumber": "321456879" 
     } 
    ] 
} 

您發送的信息:

{ 
    "empID": "101", 
    "fullname": "John Doe", 
    "contactnumber": [ 
     "444-1234", 
     "0911-124-7854" 
    ] 
} 

所以,你需要你的JS送類型的字典的數組。 你也可以調整一些領域的關係要做到這一點,但它是一個有點複雜,因爲你既需要員工ID和電話號碼,以檢查單一性。

+0

我使用angularjs使員工序列化的數據模型。並感謝指出陣列與字典的問題。現在我所需要做的就是使contactnumber成爲一個字典而不是數組。 –

相關問題