【问题标题】:Add additional fields after phone number lookup in the database in Django在 Django 中的数据库中查找电话号码后添加其他字段
【发布时间】:2019-07-15 23:49:05
【问题描述】:

我正在构建一个在数据库中查找每个电话号码的应用程序。如果有任何重复,我想获取找到的第一个电话号码作为该电话号码的主记录,然后对于重复信息(姓名,位置),获取这些字段中的每一个,并将其添加到主记录电话数字字段(名称、位置),以分号分隔。

检查找到的主电话号码记录的重复信息后,结果如下所示:

Name                      Location               Phone number
Helene,Sandra             New Yok, Boston        000-000

请在下面找到我的模型:

class Document(models.Model):
    name = models.CharField(null=True, max_length=254, blank=True)
    location = models.CharField(null=True, max_length=254, blank=True)
    phone_number = models.CharField(null=True, max_length=254, blank=True)

我有点迷失了实现上述目标。任何帮助将不胜感激。

以下是我到目前为止尝试过的:(不工作)

 from django.shortcuts import render
    from .models import Document

    def index(request):
        search_number = list(Document.objects.order_by('-created').values("phone_number").distinct().order_by()) # Dictionary list of all numbers sorted by creation data without duplicate

        for x in search_number:
            try:
                look_up = Document.objects.values("phone_number")
                list_in_dba = look_up.phone_number
                x in list_in_dba['phone_number']
                print("Yes")
            except:
                print("No")

        return render(request, 'snippets/index.html')   

【问题讨论】:

  • 到目前为止你尝试了什么?
  • @ferrix 我创建了一个电话号码字典查询集。我试图找到正确的第二个查询集来检查数据库中的电话号码是否属于该字典以对其应用逻辑。考虑使用 map 函数来检查字典的所有元素并将相同的函数应用到字典中。我无法创建第二个查询集。我在这里做对了吗?
  • 您可以添加您尝试过的查询集过滤以根据您的要求获取记录吗?
  • @Angela 我已经用上面我尝试过的代码编辑了帖子。我正在使用 print 来监控返回内容的行为。
  • @CurtisBanks 你检查过我的答案了吗?

标签: python django python-3.x django-queryset searchqueryset


【解决方案1】:

我会从这样的事情开始。

## this will get you all document records that have a duplicate phone-number 
## and also group them by phone-number.
duplicate_phone_numbers = Document.objects.values('phone_number').\
    annotate(total_items=Count('phone_number')).order_by('-total_items').filter(total_items__gt=1)

for entry in duplicate_phone_numbers:
    records = Document.objects.filter(phone_number=entry.get('phone_number')
    ## unsure whether you want to just output the info here or 
    ## update the actual record
    all_names = ''
    all_locations = ''
    for x in records:
        all_names += x.name + ";"
        all_locations += x.location + ";"
    print all_names, all_locations, entry.get('phone_number')
    # to update the actual record
    record = records[0]
    record.name = all_names
    record.location = all_locations
    record.save()

【讨论】:

    猜你喜欢
    • 2020-12-10
    • 2010-12-19
    • 2021-12-02
    • 1970-01-01
    • 2011-11-15
    • 2022-10-01
    • 2022-10-19
    • 1970-01-01
    相关资源
    最近更新 更多