2017-01-24 22 views
0

這個問題在整個互聯網上都有評論,但我不知道爲什麼,它幾乎總是和用戶在一起。違反非空約束。用ForeighKey(不是用戶)試圖在Django RestFramework中發佈

在我的情況下,問題不在用戶。

我有這樣的模式:

class DocumentDetail(models.Model): 
    date = models.DateTimeField(_('date'), auto_now_add=True) 
    note = models.TextField(_('note'), blank=True) 
    checked = models.BooleanField(_('checked'), default=False) 
    details_sample = models.ForeignKey(DocumentDetailSample, related_name='details_sample', 
             verbose_name=_("details_sample"), blank=False) 
    user_id = models.ForeignKey(User, related_name='document_user_id', verbose_name=_('document_user_id'), blank=False) 

    class Meta: 
     ordering = ('date',) 

在那裏我可以用戶DocumentDetailSample領域。

的問題是,與用戶,我可以這樣做:

def perform_create(self, serializer): 
    serializer.save(user_id=self.request.user) 

def perform_update(self, serializer): 
    serializer.save(user_id=self.request.user) 

但隨着details_sample它應該是在後過去了,因爲我無法知道哪個「details_sample」是應該的。

這就是爲什麼我認爲我可以在帖子正文中通過id

{ 
    "note" : "Oh, nice", 
    "checked": "True", 
    "details_sample": "1" 
} 

但我得到這個錯誤:

django.db.utils.IntegrityError: null value in column "details_sample_id" violates not-null constraint DETAIL: Failing row contains (9, 2017-01-24 14:43:58.75642+00, Oh, nice, t, 2, null).

所以一切,但details_sample工作。 :(

下面是該行:

"1";"2017-01-24 14:40:37.881802+01";"Life is beautiful";"''";"1";"The life is beautiful. And there's also a movie";"This is about life";"{"name": "Chuck", "phone": "123"}" 

有誰知道我能怎麼辦呢

編輯

這裏是我的串行:

class DocumentDetailSerializer(serializers.ModelSerializer): 
    title = serializers.ReadOnlyField(source='details_sample.title') 
    icon = serializers.ReadOnlyField(source='details_sample.icon') 
    priority = serializers.ReadOnlyField(source='details_sample.priority') 
    description = serializers.ReadOnlyField(source='details_sample.description') 
    prefix = serializers.ReadOnlyField(source='details_sample.prefix') 
    advertise = serializers.ReadOnlyField(source='details_sample.advertise') 

    class Meta: 
     model = DocumentDetail 
     fields = (
      'url', 'id', 'date', 'icon', 'checked', 'priority', 'title', 'note', 'description', 'prefix', 'advertise' 
     ) 

我能夠在管理網站上做到這一點,但我可以「使用」整個事例。問題是在POST時。 GET也很好用。

+0

你的序列化器是什麼樣的? – Linovia

+0

就是這樣。感謝您的回答:) –

回答

1

您的序列化程序中沒有任何details_sample字段,因此它只是從數據中丟棄。

+0

不,這是真的:)我測試了它,看看。那就對了。謝謝!它檢測到,這是一個實例,即使我只寫一個Int。再次感謝! –

1

我解決它在視圖集中

def perform_create(self, serializer): 
    serializer.save(
     details_sample=DocumentDetailSample.objects.filter(Q(id=self.request.data['details_sample']))[0], 
     user_id=self.request.user) 

這不是漂亮寫這一點,但它的工作原理。如果有人知道更好的方法,請告訴我。

相關問題