简体   繁体   English

在 Django 数据库中查找电话号码后添加其他字段

[英]Add additional fields after phone number lookup in the database in Django

I am building an app that look for each phone number in the database.我正在构建一个应用程序,用于查找数据库中的每个电话号码。 If there is any duplicate, I want to grab the first phone number found as the main record for that phone number, then for the duplicate information(name, location), get each one of those fields, and add it to the main record phone number fields (name, location), separated by a semi colon.如果有任何重复,我想获取找到的第一个电话号码作为该电话号码的主要记录,然后获取重复信息(姓名,位置),获取这些字段中的每一个,并将其添加到主要记录电话数字字段(名称、位置),以分号分隔。

The outcome would look like this after checking the duplicate information of the main phone number record found:检查发现的主电话号码记录的重复信息后,结果将如下所示:

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

Please find my model below:请在下面找到我的模型:

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)

I am a bit lost on to achieve the above.我对实现上述目标有点迷茫。 Any help would be much appreciated.任何帮助将非常感激。

Below is what I have tried so far:(not working)以下是我迄今为止尝试过的:(不工作)

 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')   

I would start with something like this.我会从这样的事情开始。

## 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()

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM