2017-02-27 71 views
0

從Django 1.7升級到1.10和Django Rest Framework 3.5.4後出現問題。問題是,當我嘗試權利要求憑證,所述endopint/calims返回500錯誤與文本:在IntegrityError /權利要求中(1048,「列‘USER_ID’不能爲空」)在Django中保存模型時發送當前用戶

在urls.py這條路線被添加像這樣:

url('^claims', v.ClaimList.as_view(), name='claim_list') 

及相關部件從views.py文件:

class ClaimSerializer(serializers.ModelSerializer): 
    company_name = s.ReadOnlyField(source="ad.company.name") 
    company_address = s.ReadOnlyField(source="ad.company.address") 

    ad_thumbnail = ThumbnailField(source="ad.picture", size="200x200", read_only=True) 

    class Meta: 
     exclude = ('user',) 
     model = m.Claim 


class ClaimSerializerDeep(ClaimSerializer): 

    class Meta: 
     exclude = ('user',) 
     model = m.Claim 
     depth = 2 


class ClaimSerializerFlat(ClaimSerializer): 
    class Meta: 
     exclude = ('user',) 
     model = m.Claim 


@permission_classes((IsAuthenticated,)) 
class ClaimList(Limitable, generics.ListCreateAPIView): 
    model = m.Claim 

    def get_queryset(self): 
     tab = self.request.GET.get("tab", "active") 
     q = m.Claim.objects.filter(user=self.request.user.pk) 
     if tab == "active": 
      q = q.filter(redeemed=False, ad__end__gte=dt.date.today()) 
     elif tab == "used": 
      q = q.filter(redeemed=True) 
     return self.limit(q) 

    def pre_save(self, obj): 
     obj.user = self.request.user 

    def get_serializer_class(self): 
     if self.request.method == "POST": 
      return ClaimSerializerFlat 
     else: 
      return ClaimSerializerDeep 

而且索賠模式是:

class Claim(models.Model): 
    ad = models.ForeignKey("Ad") 
    user = models.ForeignKey(settings.AUTH_USER_MODEL) 
    created = models.DateTimeField(auto_now_add=True) 
    redeemed = models.BooleanField(default=False) 

    def save(self, *args, **kwargs): 
     increase_claimed = False 
     if self.pk is None: 
      increase_claimed = True 
     self.user = User.objects.first() # Temporary hack so that it won't crash 
     super(Claim, self).save(*args, **kwargs) # here is where it crashes 
     if increase_claimed: 
      self.ad.claimed += 1 
      self.ad.save() 

    def __unicode__(self): 
     if self.redeemed: 
      redeemed = u"Redeemed" 
     else: 
      redeemed = u"Not redeemed" 

     return u"{0} - {1} - {2}".format(self.user.email, self.ad.title, redeemed) 

    class Meta: 
     ordering = ("-id",) 

你有什麼想法嗎?

+0

''q = m.Claim.objects.filter(user = self.request.user.pk)''。您的模型中的用戶屬性是用戶對象的外鍵,但在視圖中,您使用「user = self.request.user.pk」這只是一個id號? – AspiringMat

回答

4
user = models.ForeignKey(settings.AUTH_USER_MODEL) 

您的模型需要用戶設置,但顯然它不是(已經)。

問題是爲什麼?

看你的代碼,這個作用似乎是相關線路:

def pre_save(self, obj): 
    obj.user = self.request.user 

假設你也升級DRF這是很合理的,這不工作了:http://www.django-rest-framework.org/topics/3.0-announcement/#changes-to-prepost-save-hooks

所以,你必須適應您的代碼並按文檔中的說明使用perform_create

+0

完美,它的作品。謝謝!沒有發現DRF的變化 –

+0

好的,太棒了!爲了結束這一章,將答案標記爲已接受可能是有意義的;-) – arie

相關問題