Update a Model Field when DetailView encounter. [Django]

前端 未结 2 1489
遥遥无期
遥遥无期 2021-01-28 06:22

I have a DetailView something like in views.py:

views.py

class CustomView(DetailView):
    context_object_name = \'content\'
          


        
2条回答
  •  终归单人心
    2021-01-28 06:58

    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
    

提交回复
热议问题