我試圖獲取django中的某個對象的id,但我不斷收到以下錯誤 異常值:QuerySet;對象沒有屬性ID。 我在views.pyQuerySet,對象沒有屬性ID - Django
@csrf_exempt
def check_question_answered(request):
userID = request.POST['userID']
markerID = request.POST['markerID']
title=request.POST['question']
m = Marker.objects.get(id=markerID)
u = App_User.objects.get(id=userID)
print userID
print markerID
print title
# userID='1'
# markerID='1'
# title='Hello'
at = AttachedInfo.objects.filter(attachedMarker=m.id, title=title)
print 'user'
print u.id
print 'marker'
print m.id
print 'att'
print at
#print at.id
if(Answer.objects.filter(marker=m.id, user=u.id, attachedInfo=at.id)):
print 'pass'
return HttpResponse('already answered')
else:
print 'not'
return HttpResponse('not answered yet')
誤差函數在如果條件發生在該部分(attachedInfo = at.id)。我檢查,因爲當我從條件中刪除它,一切工作正常。
這裏的models.py
class AttachedInfo(models.Model):
title = models.CharField(max_length=200)
helpText = models.CharField(max_length=200, null=True, blank=True)
type = models.CharField(max_length=200)
attachedMarker = models.ForeignKey(Marker)
answer1 = models.CharField(max_length=200, null=True, blank=True)
answer2 = models.CharField(max_length=200, null=True, blank=True)
answer3 = models.CharField(max_length=200, null=True, blank=True)
answer4 = models.CharField(max_length=200, null=True, blank=True)
correctAnswer = models.CharField(max_length=50, null=True, blank=True)
optionalMessage = models.CharField(max_length=200, null=True, blank=True)
def __unicode__(self):
return self.title
class Answer(models.Model):
user = models.ForeignKey(App_User)
app = models.ForeignKey(App, null=True, blank=True)
marker = models.ForeignKey(Marker)
attachedInfo = models.ForeignKey(AttachedInfo)
textAnswer = models.CharField(max_length=200, null=True, blank=True)
mcqAnswer = models.CharField(max_length=200, null=True, blank=True)
answered = models.BooleanField(default=False)
def __unicode__(self):
return self.attachedInfo.title
任何幫助,爲什麼我得到這個錯誤?
這可能會引發錯誤。爲了適當地處理它,做一個'.filter'然後'[0]' – karthikr
如果queryset有0個元素它會返回什麼? – EsseTi
你必須檢查空的查詢集,然後做一個[0]這就是我的意思。 – karthikr