如何使用Django插入元素



将变量插入django的字段的最佳方法是什么,类似于将元素插入python中的列表中。

我不是要在数据库中更新记录字段" first_name",而是要从数据库中的其他人中的其他人中的其他人插入" insert"或"添加"第二个" first_name"。

ex:

First Name      Last Name
    Alan            Smith
    Eric            Jones
    Inna            Smith

结果:

First Name         Last Name
    Alan, Inna      Smith, Smith
    Eric            Jones

我正在使用PostgreSQL作为数据库。

任何帮助将不胜感激。谢谢。

这就是我想出的。希望它有帮助。

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

您可以使用arrayfield链接

尝试此操作

相关内容

  • 没有找到相关文章

最新更新