2016-12-16 27 views
0

我一直有問題通過使用Django Rest Framework與嵌套序列化器傳遞附加屬性。將附加屬性一直傳遞到嵌套序列化器

我創建了一個文檔模型有一個ForeignKey 所有者 /創造者的關係等幾個ForeignKey的相關機型。這些其他型號中的一些還具有所有者 /創建者ForeignKey關聯。

class Document(models.Model): 
    owner = models.ForeignKey('auth.User',related_name='document') 
    candidate = models.ForeignKey(
            Candidate, 
            on_delete=models.CASCADE, 
            blank=True, 
            null=True, 
           ) 

class Candidate(models.Model): 
    owner = models.ForeignKey('auth.User', related_name='candidates') 
    first_name = models.CharField(max_length=30, blank=True, null=True) 

當保存下來文檔模型嵌套串行器和一個自定義create()方法,我可以通過各個領域的下降,但是,嵌套模型似乎並沒有能夠拿起所有者場,無論我如何傳遞它。單獨創建一個候選人是好的。

class CandidateSerializer(serializers.ModelSerializer): 
    owner = serializers.ReadOnlyField(source='owner.username') 
    class Meta: 
     model = Candidate 
     fields = (
       'pk', 
       'first_name', 
       'owner', 
      ) 

class DocumentSerializer(serializers.ModelSerializer): 
    owner = serializers.ReadOnlyField(source='owner.username') 
    candidate = CandidateSerializer(required=True) 
    class Meta: 
     model = Document 
     fields = (
        'owner', 
        'candidate', 
       ) 

    def create(self, validated_data): 
     candidate_data = validated_data.pop('candidate') 
     document = Document.objects.create(**validated_data) 
     Candidate.objects.create(**candidate_data) 

隨着DocumentSerializer設立這樣,我得到這樣的錯誤,同時試圖做一個POST嵌套領域的文件。

IntegrityError: NOT NULL constraint failed: dossier_candidate.owner_id 

當我修改DocumentSerializer.create()方法來嘗試拿起主人,似乎owner = serializers.ReadOnlyField(source='owner.username')現在是超出範圍,即使它應該是類下。

當我嘗試用

Candidate.objects.create(owner, **candidate_data) 

創建對象的候補我得到這個錯誤:

NameError at /rest/documents/ 
global name 'owner' is not defined 

當我嘗試這個

Candidate.objects.create(self.owner, **candidate_data) 

我得到這個錯誤:

AttributeError: 'DocumentSerializer' object has no attribute 'owner' 

什麼是確保嵌套候選對象能夠成功創建,拿起所有者字段的正確方法?

回答

0

首先,您不會讓擁有者創建/更新,因爲它是隻讀的。

如果您想獲取當前用戶,請使用CurrentUserDefault。它將被添加到validated_data