I have a Django model, shown below, that I use to keep track of which ip addresses visit my site and when.
class Visit(models.Model):
created = models.DateTimeField(default=datetime.utcnow)
ip = models.IPAddressField(editable=False)
I'd like to write a method on this model that returns the number of days in took for the last 100 visits from a particular IP. Multiple visits in a single d开发者_开发技巧ay (hour etc) from an IP all count as separate visits. So, if someone visted the site 100 times in the past 2 days, it would return 2, 100 times in the past 8 days, it would return 8, and so on.
You probably want to change the default= for created_on to be auto_now_add since the datetime.utcnow doesn't update if you're using servers other than the dev server:
class Visit(models.Model):
created = models.DateTimeField(auto_now_add=True,editable=False)
ip = models.IPAddressField(editable=False)
from datetime import datetime
def days_for_100(ip_addr):
now = datetime.now()
dates = Visit.objects.filter(ip=ip_addr)
if dates.count()<100:
latest = dates.latest('-created')
else:
latest = dates.dates('created','day',order='DESC')[99]
return (now-latest).days # timedelta.days
This returns how many days earlier the 100th visit ago happened (or how long ago the first visit occurred if there are less than 100 visits)
An easy approach is to get the last 100 Visit objects for an ip address and count the number of unique created
objets in them.
def num_of_dates(ip_addr)
dates = [v.created for v in Visit.objects.filter(ip=ip_addr).order_by('-created')[0:100]]
unique_dates = set(dates)
return len(unique_dates)
精彩评论