Reputation: 827
I ask myself this question, what the difference and the more performant between a method in models.py and views.py ?
Example 1:
models.py:
class Counter(models.Model):
number = models.PositiveSmallIntegerField(default=0)
def add_one(self):
self.number += 1
self.save()
views.py
from *xxx* import Counter
def count(request):
c = Counter()
c.add_one()
c.save()
return render(request, *xxx*)
Example 2:
models.py:
class Counter(models.Model):
number = models.PositiveSmallIntegerField(default=0)
views.py
from *xxx* import Counter
def add_one(nb):
nb += 1
return nb
def count(request):
c = Counter()
c.number = add_one(c.number)
return render(request, *xxx*)
My example is a little bit simple, but what the difference in the real life with big method and so many variables ?
Its have an impact on the performance of the server ? Did he have conventional or preference to choose one way ?
Upvotes: 2
Views: 1122
Reputation: 53734
both approaches are wrong!
The correct way is
Counter.objects.filter(pk=some_id).update(number=F('number')+1)
Note that this approach is needed to avoid race conditions. your current approach would need transactions to make it work properly. Code like the above typically go into the view.
Upvotes: 4