Django 会在 process_response 之后展平响应吗?
我有这个模型(简化版):
class Ticket(models.Model):
uuid = UUIDField(primary_key = True)
is_active = models.BooleanField(default = False)
remains = models.IntegerField(default = 2)
def __unicode__(self):
return '%s' % (self.is_active)
和中间件(简化):
class TicketMiddleware(object):
def process_request(self, request):
# ...
try:
request.ticket = Ticket.objects.get(uuid_exact=request.GET['ticket'], is_active=True)
print '%s %d' % (request.ticket.is_active, request.ticket.remains)
# first case:
return HttpResponse(request.ticket)
# second case:
#return HttpResponse(request.ticket.is_active)
except Ticket.DoesNotExists:
return HttpResponseForbidden()
def process_response(self, request, response):
if request.ticket is not None and request.ticket.remains > 0:
request.ticket.remains -= 1
if request.ticket.remains == 0:
request.ticket.is_active = False
request.ticket.save()
return response
在第一种情况下,我在第四次请求时获得了禁止页面:
RESPONSE PRINT
1: True True 2
2: False True 1
3: False True 1
4: Forbidden
在第二种情况下,我在第三次请求时获得了禁止页面:
RESPONSE PRINT
1: True True 2
2: True True 1
3: Forbidden
这第二种情况是我想要的方式。为什么我必须首先对模型进行字符串化才能正常流动?我误解了什么?
django.VERSION = (1, 2, 3, 'final', 0)
编辑
我发现了问题。在实际代码中,我为 django.contrib.auth.models.User 使用外键,并使用关联用户的用户名对我的 Ticket 模型进行 unicoding:
class Ticket(models.Model):
# ...
user = models.ForeignKey(User)
def __unicode__(self):
# this works as expected
return u'%s' % (self.is_active)
# with this I have unexpected third step in first case
# but I dont understand why
#return u'%s %s' % (self.user.username, self.is_active)