Добавить дополнительные поля после поиска номера телефона в базе данных в Джанго
Я создаю приложение, которое ищет каждый номер телефона в базе данных. Если есть какой-либо дубликат, я хочу взять первый номер телефона, найденный в качестве основной записи для этого номера телефона, а затем для дубликата информации (имя, местоположение), получить каждое из этих полей и добавить его в основной записи телефона числовые поля (имя, местоположение), разделенные точкой с запятой.
Результат будет выглядеть следующим образом после проверки дубликата найденной записи основного номера телефона:
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')
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()