简体   繁体   English

如何使用Django将元素插入字段

[英]How to insert element into a field with django

What would be the best way to insert a variable into a field in django, similar to insert element into a list in python. 将变量插入django中的字段的最佳方法是什么,类似于将元素插入python中的列表的最佳方法。

I am not trying to update a record field "first_name" in the database but rather "insert" or "add" a second "first_name" from someone else in the database that share the same last name. 我不是要更新数据库中的记录字段“ first_name”,而是要从数据库中共享相同姓氏的其他人“插入”或“添加”第二个“ first_name”。

Ex: 例如:

First Name      Last Name
    Alan            Smith
    Eric            Jones
    Inna            Smith

Result: 结果:

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

I am using PostgreSQL as database. 我正在使用PostgreSQL作为数据库。

Any help would be much appreciated. 任何帮助将非常感激。 Thank you. 谢谢。

This is what I came up with. 这就是我想出的。 Hope it helps. 希望能帮助到你。

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 链接

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM