[Answer]-Django ORM most occuring value

1👍

IMHO you’re better off with a many-to-many relationship. You would have something like:

class VisitedURLs(models.Model):
    page = models.ForeignKey(Visitor, ....)
    user = models.ForeignKey(User, ....)
    timestamp = models.DateTimeField(auto_now_add=True)

and the original models become something like:

class Visitor(models.Model):
    members = models.ManyToManyField(PageView, through='VisitedURLs')

class PageView(models.Model):
    url = models.CharField(max_length=500)
    method = models.CharField(max_length=20, null=True)

In this case, you can use the count/distinct on the visitedURLs model and when you get an object of that type you’ll have a FK to a Visitor object (which would give you the user…) and a FK to the URL.

Another way is to explicitly count each unique visitor/url combination and store it somewhere. Depending on usage (e.g. if you want to compute/display this often) you may be better off with the dedicated storage.

0👍

Here is the solution that i have come up with.

Pageview.objects.filter(visitor__user_id=user['visitor__user_id']).values(
                'url').annotate(page_count=Count('id')).order_by('-page_count')
 if max_visited_node:
                user['max_visited_node'] = max_visited_node[0]

by this way i can get the count of the all the pages the user have visited. then i order them by that count and then i get the top first element which contains the URL and page_count.

This is what i was looking for. the suggestion of Laur lvan is worth considerable.

👤A.J.

Leave a comment