Update a Model Field when DetailView encounter. [Django]

前端 未结 2 1511
遥遥无期
遥遥无期 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

    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.

提交回复
热议问题