Hi I have an application which checks and counts searched terms by updating a counter if the query has already been searched and inserts a field with counter=1 if the query is new.
The search counter model:
class Search(models.Model):
term = models.CharField(unique=True, max_length=255)
counter = models.IntegerField()
last_search = models.DateTimeField()
and a view containing this:
# update search counter with term
try:
term = Search.objects.get(term=query)
except Search.DoesNotExist:
term = None
if term:
term.counter = F('counter') + 1
term.last_search = datetime.now()
else:
term = Search(
term=query,
counter=1,
last_search = datetime.now()
)
term.save()
My question is really – is this a good way to do this and is there a more concise way to put it? It seems overly ugly to me, and being a Django novice I would like to see a ‘best practice’ implementation of the same. Any answers appreciated.
Here’s a more concise version (you might need to set “default=0” on the counter field):
You don’t need to set all the values in the constructor – as long as they’re all there by the time you save or validate.