遇到DetailView时更新模型字段.[Django] [英] Update a Model Field when DetailView encounter. [Django]

查看:31
本文介绍了遇到DetailView时更新模型字段.[Django]的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在 views.py 中有一个DetailView:

I have a DetailView something like in views.py:

views.py

class CustomView(DetailView):
    context_object_name = 'content'
    model = models.AppModel
    template_name = 'dynamictemplate.html'

    def get_context_data(self, **kwargs):
        data = super(CustomView, self).get_context_data(**kwargs)
        <...snipped...>
        return data

urls.py 的请求转移到 views.py 时,如何更新模型字段( IntegerField ).假设IntegerField的名称为 clicks ,当用户访问特定链接或被动访问数据库中的模型对象时,该如何增加该对象的 clicks 字段通过1.

How could I update the model field, an IntegerField when the request from urls.py transfers to views.py. Let's suppose the name of IntegerField is clicks and when a user visits a particular link or passively, a model object from database, then how could I increment the clicks field of that object by 1.

推荐答案

您可以使用 self.object 并通过以下方式进行更新:

You can use self.object and update it this way:

self.object.clicks = self.object.clicks + 1
self.object.save()

但是正如丹尼尔(Daniel)在评论中所说,使用此代码,您可能会遇到 F表达式 像这样:

But as Daniel said in comment, using this code you can faced race condition. So it would be better to use F expressions like this:

from django.db.models import F

def get_context_data(self, **kwargs):
    data = super(CustomView, self).get_context_data(**kwargs)
    self.object.clicks = F('clicks') + 1
    self.object.save()
    <...snipped...>
    return data

这篇关于遇到DetailView时更新模型字段.[Django]的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆