I have a logging table in my app, that shows how/when listed items were viewed. The same logging table also logs different types of clickthroughs, and will probably (in the future) log edits, etc. So far, the logging seems to work as I expect. Because the same logging table is used for different actions, and its results are also related to different tables (according to the action taken) it doesn’t seem to me that Django really likes that kind of setup, ie a couple of records might look like this:
id fkey vtype ip…
1. 30. edit. 192.168.1.1
2. 30. click. 10.0.0.1
Where the fkey
is the id in another table and vtype is the class of item logged – actually vtype is the name of a url
in urls.py
. As you can see the fkeys
in different tables can clash, so when retrieving data one also has to look for the vtype
, so as to get the relevant data.
I want to use the data from the logging to display on a page the number of visits that page has had over a 30 day period. Because this logging data is not directly related to the page
model, I put a method in the page
model to retrieve the data:
models.py
class Page(models.Model):
...
@property
def viewcount(self):
timeoffset = (datetime.now(timezone.utc) - timedelta(days=30))
thecount = Viewlog.objects.filter(fkey=self.id,vtype='page',moddate__gte=timeoffset).count()
return thecount
This works, in that I can put {{ object.viewcount }}
on a template and it shows relevant data.
However, I have three questions:
-
Is this the correct way to put arbitrary data on a template?
-
Because
viewcount
is a property of thepage
model I think it is getting called/created every time the model is accessed, which is ok for a detail view, but not a really great idea for a list view. Can I differentiate when this property is called? -
As you will note, in setting
the count
variable, thevtype
value is a hard coded string"page"
. When the log entry saved into the table, the method that does that enters thevtype
string from the url name:
vtype=(request.resolver_match.url_name)
I would like to be able to do that in the log query too, but cannot work out how to get the request
parameter into the viewcount
method. Either request
is not available, or it causes an exception if I put it in the expected parameters.
I have tried to get the url name in other ways, eg by using self.get_absolute_url
and then trying to resolve that, but that seems to produce 404
errors.
Any guidance gratefully received.