在django中将变量插入字段的最佳方式是什么,类似于在python中将元素插入到列表中。
我并不是试图更新数据库中的记录字段"first_name“,而是”插入“或”添加“来自数据库中共享相同姓氏的其他人的第二个"first_name”。
例如:
First Name Last Name
Alan Smith
Eric Jones
Inna Smith结果:
First Name Last Name
Alan, Inna Smith, Smith
Eric Jones我使用PostgreSQL作为数据库。
任何帮助都将不胜感激。谢谢。
发布于 2019-02-28 03:15:43
这就是我想出来的。希望能有所帮助。
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()发布于 2019-02-25 22:24:45
您可以在ArrayField link中尝试此操作
https://stackoverflow.com/questions/54867943
复制相似问题