增量模型字段内部获取或创建 Django

我正在开发一个音乐Web应用程序,我试图计算一首歌的播放次数。单击播放按钮时,将调用一个名为的函数。在这里,我尝试使用来更新模型,如下所示。getLink()get_or_createPlayCount


h = PlayCount.objects.all()


    if len(h) == 0:

        u = PlayCount.objects.get_or_create(

            user=request.user.username,

            song=song,

            plays=1,

        )[0]

        u.save()


    else:


        flag = False


        for i in h:

            if i.song == song:

                u = PlayCount.objects.get_or_create(

                    user=request.user.username,

                    song=song,

                    plays=plays + 1,

                )[0]

                u.save()

                flag = True

                break

            else:

                pass


        if flag is False:

            u = PlayCount.objects.get_or_create(

                user=request.user.username,

                song=song,

                plays=1,

            )[0]

            u.save()

        else:

            pass

但是,当我进入 else 循环时,返回 。127.0.0.1:8000play is not defined


我该如何继续?


人到中年有点甜
浏览 115回答 1
1回答

蝴蝶不菲

我不明白为什么你循环遍历所有对象,而你所需要的只是找到特定和.PlayCountusersong另请注意,只会找到与您传递给它的所有参数匹配的特定对象,因此将尝试查找具有您指定的确切播放次数的对象,该对象不是您想要的。get_or_createget_or_create(user=..., song=..., plays=...)您只需执行以下操作:from django.db.models import Fplay_counter, created = PlayCount.objects.get_or_create(    user=request.user,    song=song,    defaults={'plays': 1})if not created:    play_counter.plays = F('plays') + 1    play_counter.save()因此,在这里,我们首先获取或创建特定歌曲和用户的计数器。如果我们创建它,我们通过在参数中设置它来设置为1。playsdefaults然后,如果未创建它(即它是现有的),我们使用表达式递增1,这可确保它直接在数据库中更新(并且如果另一个请求正在更新相同的值,则不会有数据库不一致的风险)。playsF
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Python