如何使用django将元素插入到字段中
How to insert element into a field with django
在 django 中将变量插入字段的最佳方法是什么,类似于 python 中将元素插入列表。
我不是要更新数据库中的记录字段 "first_name",而是 "insert" 或 "add" 每秒 "first_name" 来自数据库中共享的其他人相同的姓氏。
例如:
First Name Last Name
Alan Smith
Eric Jones
Inna Smith
结果:
First Name Last Name
Alan, Inna Smith, Smith
Eric Jones
我正在使用 PostgreSQL 作为数据库。
如有任何帮助,我们将不胜感激。谢谢。
你可以用 ArrayField 试试这个 link
这是我想到的。希望对你有帮助。
to_delete = []
for person in Person.objects.all():
# all people sharing a last name with person
matches = Person.objects.filter(last_name=person.last_name)
# a list with the first names
first_names = matches.values_list('first_name', flat=True)
# a list with the last names
last_names = matches.values_list('last_name', flat=True)
# Join them with comma as a separator e.g 'Alan, Inna'
joined_fnames = ', '.join(first_names)
joined_lnames = ', '.join(last_names)
# set the new joined strings as persons new values
person.first_name = joined_fnames
person.last_name = joined_lnames
# get the other record ids that have already been joined into person and add to to_delete
ids = matches.exclude(id=person.id).values_list('id', flat=True)
to_delete += ids
person.save()
# finally delete all records in to_delete
Person.objects.filter(id__in=to_delete).delete()
在 django 中将变量插入字段的最佳方法是什么,类似于 python 中将元素插入列表。
我不是要更新数据库中的记录字段 "first_name",而是 "insert" 或 "add" 每秒 "first_name" 来自数据库中共享的其他人相同的姓氏。
例如:
First Name Last Name
Alan Smith
Eric Jones
Inna Smith
结果:
First Name Last Name
Alan, Inna Smith, Smith
Eric Jones
我正在使用 PostgreSQL 作为数据库。
如有任何帮助,我们将不胜感激。谢谢。
你可以用 ArrayField 试试这个 link
这是我想到的。希望对你有帮助。
to_delete = []
for person in Person.objects.all():
# all people sharing a last name with person
matches = Person.objects.filter(last_name=person.last_name)
# a list with the first names
first_names = matches.values_list('first_name', flat=True)
# a list with the last names
last_names = matches.values_list('last_name', flat=True)
# Join them with comma as a separator e.g 'Alan, Inna'
joined_fnames = ', '.join(first_names)
joined_lnames = ', '.join(last_names)
# set the new joined strings as persons new values
person.first_name = joined_fnames
person.last_name = joined_lnames
# get the other record ids that have already been joined into person and add to to_delete
ids = matches.exclude(id=person.id).values_list('id', flat=True)
to_delete += ids
person.save()
# finally delete all records in to_delete
Person.objects.filter(id__in=to_delete).delete()