【发布时间】:2015-03-20 18:13:07
【问题描述】:
在 Django 中,是否可以使用查询集和正则表达式查找重复项?
Django select only rows with duplicate field values 显示不使用正则表达式:
self.values('Website').annotate(count=Count('id')).order_by().filter(count__gt=1)
我有一个模型:
class company(models.Model):
Website = models.URLField(blank=True, null=True )
我想用正则表达式查找重复项
例如。
Company.objects.create(Website='http://example.com')
Company.objects.create(Website='http://www.example.com')
这两个是同一个网站。我想使用正则表达式,以便它将这些公司作为重复返回。
我知道有这样的过滤器使用正则表达式。我不确定如何更新它以使用正则表达式:
self.values('Website').annotate(count=Count('id')).order_by().filter(count__gt=1)
我想做这样的事情:
Website__iregex='http[s]?://(?:[a-zA-Z]|[0-9]|[$-_@.&+]|[!*\(\),]|(?:%[0-9a-fA-F][0-9a-fA-F]))+'
更新 有一些混乱,所以我举个例子。
这是我的数据库的样子
Company.objects.create(Website='http://example.com')
Company.objects.create(Website='http://www.example.com')
Company.objects.create(Website='http://example.org', Name='a')
Company.objects.create(Website='http://example.org', Name='b')
当我打电话时
Company.objects.all().values('Website').annotate(count=Count('id')).order_by().filter(count__gt=1)
返回:
- http://example.org(来自 name=a)和http://example.org(来自 name=b)
这缺少 example.com 和 www.example.com 是同一个网站。
我想使用正则表达式,以便告诉 django example.com 和 www.example.com 是同一个网站。
我要修改:
Company.objects.all().values('Website').annotate(count=Count('id')).order_by().filter(count__gt=1)
以便它返回重复项:
http://example.org(来自 name=a)和http://example.org(来自 name=b)
example.com www.example.com
【问题讨论】:
-
这
.annotate(count=Count('id')).order_by().filter(count__gt=1)是否有效???