我有一些代码设置来计算页面点击次数,每次点击页面时数据都会存储在 ObjectViewed 模型中。 我目前正在计算每个页面被点击的次数,但我希望使其成为唯一的页面点击次数,因此每个 IP 每页仅显示 1 次点击。
我正在尝试过滤掉 ip_address 和 content_object 在一行中多次出现的位置。
class ObjectViewed(models.Model):
object_id = models.PositiveIntegerField()
content_type = models.ForeignKey(ContentType, on_delete=models.SET_NULL, null=True)
#where these are together i want to only count once below
content_object = GenericForeignKey('content_type', 'object_id')
ip_address = models.CharField(max_length=120, blank=True, null=True)
def analytics(request):
objects = ObjectViewed.objects.all()
q = NewsPost.objects.values('id').distinct()
dict = {}
for object in q:
dict.update({list(object.values())[0]: 0})
count = ObjectViewed.objects.values('object_id').annotate(c=Count('object_id')).order_by('-c')
尝试了一些东西,但对 python 和 django 来说是新的,所以我不太确定最好的方法是什么。 任何帮助/指导将不胜感激,谢谢!
最佳答案
我认为你在这里让事情变得太困难了,而且你自己可能做了太多的工作。
您可以使用 Count
object [Django-doc] 的 distinct=True
参数来计算不同 ip_address
的数量。 ,例如:
from django.db.models import Count
ObjectViewed.objects.values('object_id', 'content_type').annotate(
c=Count(<b>'ip_address', distinct=True</b>)
).order_by('-c')
我们可以使用它来有效地订购 NewsPost
,例如:
from django.contrib.contenttypes.models import ContentType
from django.db.models import Count
views = <b>dict(</b>ObjectViewed.objects.filter(
content_type=get_object_for_this_type(NewsPost)
).values_list('object_id').annotate(
c=Count(<b>'ip_address', distinct=True</b>)
).order_by('object_id')<b>)</b>
然后我们可以在 Django/Python 级别对元素进行排序,如下所示:
<b>my_newsposts = sorted(</b>NewsPost.objects.all()<b>, key=views.get, reverse=True)</b>
因此,我们首先过滤以仅检索 NewsPost
对象上的不同 View ,我们将这些 View 放入名为 views
的字典中,然后我们以相反的顺序对具有该 View 的 NewsPost
对象进行排序。
关于python - 删除 python django 模块中 content_id 和 ip_address 相同的重复项,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56570958/