從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",)
你有什麼想法嗎?
''q = m.Claim.objects.filter(user = self.request.user.pk)''。您的模型中的用戶屬性是用戶對象的外鍵,但在視圖中,您使用「user = self.request.user.pk」這只是一個id號? – AspiringMat