0

将变量插入到 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 作为数据库。

任何帮助将非常感激。谢谢你。

4

2 回答 2

1

这就是我想出的。希望能帮助到你。

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-27T19:15:43.477 回答
0

你可以试试这个 ArrayField链接

于 2019-02-25T14:24:44.600 回答