【问题标题】:Convert raw SQL to Django QuerySet将原始 SQL 转换为 Django QuerySet
【发布时间】:2016-06-21 10:58:05
【问题描述】:

有人可以展示如何将以下 SQL 查询转换为 Django QuerySet 调用吗?我是 Django 新手,我可以使用原始查询,但我很高兴知道如何将此查询编写为原生 Django 调用。

有 2 个模型用户和配置文件 1:1 如果相同的电话号码出现在 2 个或更多个人资料中,我需要从用户那里获取电子邮件并从个人资料中获取电话。

SELECT GROUP_CONCAT(u.email) as emails, p.phone as phone_number FROM profile AS p JOIN auth_user AS u on u.id = p.user_id GROUP BY phone HAVING COUNT(phone) > 1

这是我尝试做的:

from myapp.models import Profile
from django.db.models import Count

Profile.objects
       .exclude(phone='')
       .annotate(phone_count=Count('phone'))
       .values('phone')

..结果是:

[
  {
    'phone': '***'
  },
  {
    'phone': '***'
  }
]

如果将.filter(phone_count__gt=1)添加到查询中,则会返回一个空结果(不明白为什么)。

想要的输出是:

[
    {
      'phone': '***',
      'emails': 'user1@mail.com'
    },
    {        
      'phone': '***',
      'emails': 'user2@mail.com,user3@mail.com'
    }
  ]

UPD

class Profile(models.Model):
    user = models.OneToOneField(User, on_delete=models.CASCADE)
    phone = models.CharField(max_length=100, blank=True, null=True)

【问题讨论】:

  • 您应该展示自己是如何尝试转换的。
  • @Sayse 添加了更多描述。
  • 如果您可以显示Profile 模型的相关部分会有所帮助,尽管您在此处显示的结果只有一个电话号码,因此为什么添加过滤器不会返回任何结果跨度>
  • @Sayse 添加了Profile 模型的一部分。所需的结果应该包含一个电话号码和一个电子邮件地址列表,但我不知道 Django 是否可以获取emails: ['user1@mail.com', 'user2@mail.com'] 的列表,所以我正在尝试使用 group_concat,但如果它可以更容易解决的话会很棒。
  • 你应该尝试创建一个minimal reproducible example,django的用户模型没有电子邮件列表,并且不清楚charfield的计数会有什么价值

标签: python django django-models django-queryset


【解决方案1】:
from myapp.models import Profile
from django.db.models import Count

qs = Profile.objects.exclude(
    phone=''
).exclude(
    phone__isnull=True
).values('phone').annotate(
    phone_count=Count('user_id')
).filter(
    phone_count__gt=1
).values_list('phone', flat=True)
# the above will get you a list of phone numbers that appear more than once
# now get the user_ids, too, and add in the emails
qs = Profile.objects.filter(phone__in=qs).values_list('user__email', 'phone')
# now convert to a dict
from collections import defaultdict
data = defaultdict(list)
for email, phone in qs:
    data[phone].append(email)
# now convert to desired format
result = [{
    'phone': phone,
    'emails': ','.join(emails),
} for phone, emails in data.itervalues()]

# Of course, you could always just use raw and do a raw
# SQL query as described here:  https://docs.djangoproject.com/en/1.9/topics/db/sql/#executing-custom-sql-directly

【讨论】:

    猜你喜欢
    • 2019-04-03
    • 1970-01-01
    • 1970-01-01
    • 2022-08-18
    • 2012-03-08
    • 2019-06-11
    • 2019-08-05
    • 1970-01-01
    • 2011-04-15
    相关资源
    最近更新 更多