【发布时间】:2016-03-01 20:21:13
【问题描述】:
我已经在 Django 上工作了一段时间,现在我遇到了这个奇怪的问题。
我正在一个流媒体网站上添加评分功能,为此我编写了一个通过 url 调用的视图:
url(r'^channel/rate/(?P<stream_id>[\d]*)/(?P<rate>[\d]*)/?$', 'eros.streaming.views.view_rate_channel',
name='view_rate_channel'),
def view_rate_channel(request,stream_id,rate):
if(stream_id and rate and request.user.is_authenticated()):
stream= Stream.objects.get(id=stream_id)
if stream not in request.user.channel.rated_streams.all():
if stream.channel.user != request.user:
channel=Channel.objects.get(stream=stream)
channel.rating= channel.rating+int(rate)
print("channel rating: "+str(channel.rating))
#this prints fine in any case
channel.n_voters = channel.n_voters +1
channel.save()
stream.rating= stream.rating+int(rate)
stream.n_voters= stream.n_voters+1
stream.save()
request.user.channel.rated_streams.add(stream)
request.user.channel.save()
return HttpResponseRedirect('/channel/'+str(stream.channel.id)+'/')
return HttpResponseRedirect('/channel/'+str(stream.channel.id)+'/')
当我检查数据库时,我在 channel.save() 之后对 Channel 对象所做的更改没有保存,只有我发现奇怪的 Stream 对象上的更改。
所以在进行了一些调试之后,我决定评论这个 if,我使用它以便用户不能对流进行多次评分:
##if stream not in request.user.channel.rated_streams.all():
现在 channel.save() 开始工作了!坏事是我不能让用户对流进行多次评分。
这是模型的简化版本:
class Channel(models.Model):
user = models.OneToOneField(User)
rating = models.IntegerField(default=0)
n_voters = models.IntegerField(default=0)
rated_streams = models.ManyToManyField('Stream', related_name="rated_streams")
description = models.TextField(default="")
class Stream(models.Model):
## I think that maybe this relation is what is causing me trouble (?):
channel = models.ForeignKey(Channel)
rating = models.IntegerField(default=0)
n_voters = models.IntegerField(default=0)
我正在做的任何不良做法或不良查询导致这种情况发生吗?提前非常感谢。
【问题讨论】:
-
当
if stream条件未注释时,Channel对象中的更改不会被保存。是这个问题吗? -
Channel.objects.get(stream=stream)是如何工作的?没有stream列是您的Channel模型。 -
另外,您确认
channel和request.user.channel是同一个对象吗? -
关于您的第二条评论,这是一件有趣的事情,因为关系是用流上的外键(一对多)建模的,通道上没有字段流。所以我尝试让通道作为参数传递流并返回它,但这是一种愚蠢的调用方式,因为我可以像 channel=stream.channel 一样做到这一点。我做到了并且知道它的工作原理!这是一种奇怪的行为。非常感谢!
-
好的,伙计!你的意思是在下面的答案中?
标签: python django django-models django-views django-queryset