首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >如何使用django在字段中插入元素

如何使用django在字段中插入元素
EN

Stack Overflow用户
提问于 2019-02-25 22:02:54
回答 2查看 122关注 0票数 0

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

我并不是试图更新数据库中的记录字段"first_name“,而是”插入“或”添加“来自数据库中共享相同姓氏的其他人的第二个"first_name”。

例如:

代码语言:javascript
运行
复制
First Name      Last Name
    Alan            Smith
    Eric            Jones
    Inna            Smith

结果:

代码语言:javascript
运行
复制
First Name         Last Name
    Alan, Inna      Smith, Smith
    Eric            Jones

我使用PostgreSQL作为数据库。

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

EN

回答 2

Stack Overflow用户

回答已采纳

发布于 2019-02-28 03:15:43

这就是我想出来的。希望能有所帮助。

代码语言:javascript
运行
复制
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()
票数 1
EN

Stack Overflow用户

发布于 2019-02-25 22:24:45

您可以在ArrayField link中尝试此操作

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/54867943

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档