Update a Model Field when DetailView encounter. [Django]

谁说胖子不能爱 提交于 2020-01-30 11:24:49

问题


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

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.


回答1:


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

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

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



回答2:


neverwalkaloner is very close, but the object needs to be refreshed from the database after it's saved.

from django.db.models import F

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

Now the value of the clicks will be displayed instead of the __repr__ of the F expression.



来源:https://stackoverflow.com/questions/50096510/update-a-model-field-when-detailview-encounter-django

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!