Django 中模型字段的值自动递增

发布于 2024-10-16 14:25:20 字数 522 浏览 2 评论 0原文

我想问一个问题,如何在 django 中增加模型字段。 假设我有一个模型叫做

对我的书签(请求)进行分类:

 url=models.URLField()
  流行度=models.IntegerField()

然后使用 Django 模板 我有

<块引用>

书签.html

{% for list_tagg % 中的数据库}

网址:{{database.url}}

<块引用>

流行度:{{database.popularity}}

{% endfor %}

现在:如果有人点击链接(即 bookmarks.html 页面中的 URL 字段),我希望流行度增加 1。我该怎么办所以?有什么帮助吗?

i want to ask a question that how can i increment a model field in django.
lets suppose i have a model called

class my bookmarks(requests):

  url=models.URLField()
  popularity=models.IntegerField()

and then by using Django template
i have

bookmarks.html

{% for database in list_tagg %}

URL:{{database.url}}

POPULARITY: {{database.popularity}}

{% endfor %}

Now: if anyone clicks on the link (i.e. the URL field in the bookmarks.html page) I would like that the popularity should be increased by 1. How can i do so? Any help?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

南风几经秋 2024-10-23 14:25:20

使用 F 场 ,)

from django.db.models import F

b = Bookmark.objects.get(pk=id_retrieved)
b.popularity = F('popularity') + 1
b.save()

Use F-fields ,)

from django.db.models import F

b = Bookmark.objects.get(pk=id_retrieved)
b.popularity = F('popularity') + 1
b.save()
不可一世的女人 2024-10-23 14:25:20

您可能想要实现 Ajax 调用来连接到服务器并记录单击。例如,使用 jQuery,您可以在每次单击时调用此 JS 函数:

function incrementPopCounter(pop_id) {
    $.ajax({type: 'POST',
            dataType: 'json',
            url: '/pop/increment',
            data: 'id=' + pop_id,
            success: function(data) {
               if(data.result == 'OK') {
                   // handle success
               } else {
                   // handle failure
               }
            }
           });
    return false;
}

处理此问题的 Django 视图可能如下所示:

from django.utils import simplejson
...
def increment_pop(request):
    if request.is_ajax():
        if 'pop_id' in request.POST and request.POST['pop_id']:
            try:
                pop = Bookmark.objects.get(pk=request.POST['pop_id'])
            except Bookmark.DoesNotExist:
                return HttpResponse(simplejson.dumps({'result': 'No bookmark by that id found.'}),
                                    mimetype='application/json')
            pop.popularity = F('popularity') + 1
            pop.save()
            return HttpResponse(simplejson.dumps({'result': 'OK'}),
                                mimetype='application/json')
        else:
            return HttpResponse(simplejson.dumps({'result': 'Unable to identify the requested bookmark.'}),
                                mimetype='application/json')
    else:
        return HttpResponseBadRequest()

You probably want to implement an Ajax call to connect to the server and record the click. For example, using jQuery, you can have this JS function called on every click:

function incrementPopCounter(pop_id) {
    $.ajax({type: 'POST',
            dataType: 'json',
            url: '/pop/increment',
            data: 'id=' + pop_id,
            success: function(data) {
               if(data.result == 'OK') {
                   // handle success
               } else {
                   // handle failure
               }
            }
           });
    return false;
}

The Django view to handle this could look like this:

from django.utils import simplejson
...
def increment_pop(request):
    if request.is_ajax():
        if 'pop_id' in request.POST and request.POST['pop_id']:
            try:
                pop = Bookmark.objects.get(pk=request.POST['pop_id'])
            except Bookmark.DoesNotExist:
                return HttpResponse(simplejson.dumps({'result': 'No bookmark by that id found.'}),
                                    mimetype='application/json')
            pop.popularity = F('popularity') + 1
            pop.save()
            return HttpResponse(simplejson.dumps({'result': 'OK'}),
                                mimetype='application/json')
        else:
            return HttpResponse(simplejson.dumps({'result': 'Unable to identify the requested bookmark.'}),
                                mimetype='application/json')
    else:
        return HttpResponseBadRequest()
妖妓 2024-10-23 14:25:20

阿尔马德的回答可以简化为以下内容:

from django.db.models import F

Bookmark.objects.get(pk=id_retrieved).update(popularity=F('popularity') + 1)

Almad's answer could be simplified to the following:

from django.db.models import F

Bookmark.objects.get(pk=id_retrieved).update(popularity=F('popularity') + 1)
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文