CSV导入到具有多对多字段的模型

时间:2022-10-04 13:52:01

I'm trying to create a simple CSV import form that imports into my model GroupMembers. The GroupMembers model has a many-to-many field that links to my Groups model. The idea is you can upload a CSV membership file for a specific group; you select a group from a dropdown on the same page as the CSV upload. A member can be a member of multiple groups so if the member already exists, it should just add the new group relationship.

我正在尝试创建一个简单的CSV导入表单,导入到我的模型GroupMembers中。 GroupMembers模型具有链接到我的Groups模型的多对多字段。您的想法是可以上传特定组的CSV成员资格文件;您可以从与CSV上传相同的页面上的下拉列表中选择一个组。成员可以是多个组的成员,因此如果该成员已存在,则应该只添加新的组关系。

My code is partially working - it adds groupmembers - but I'm having problems with the many-to-many link to Groups. Here is my code so far

我的代码部分工作 - 它添加了组成员 - 但我遇到了与组的多对多链接的问题。到目前为止,这是我的代码

models.py (group)

class Group (models.Model):
    initials = models.CharField(max_length = 20)
    initials_lower = models.CharField(max_length = 20)
    full_name = models.CharField('Full name', max_length = 100)

models.py (groupmember) - this is where the csv adds to

models.py(groupmember) - 这是csv添加的位置

from django.db import models
from datetime import datetime

class GroupMember (models.Model):
    name = models.CharField('Name', max_length = 30, unique = True)
    pub_date = models.DateTimeField('Date published', auto_now_add = True)
    groups = models.ManyToManyField('groups.Group', blank = True)

    def __unicode__(self):
        return self.name 

forms.py

from django import forms
import csv
from myproject.groupmembers.models import GroupMember
from myproject.groups.models import Group


class GroupImportForm (forms.Form):

    csv_file = forms.FileField()
    group_name = forms.ModelChoiceField(queryset=Group.objects.all())

    def save(self):
        records = csv.reader(self.cleaned_data["csv_file"])
        for line in records:
            input_data = GroupMember()
            input_data.handle = line[0]
            input_data.groups.create(initials=self.cleaned_data["group_name"]) <-- this is where the problem is
            input_data.save()

views.py (partial)

def batch_add (request):
    if request.method == 'POST':
        form = GroupImportForm(request.POST, request.FILES)
    if form.is_valid():
        form.save()
    else:
        form = GroupImportForm()

    return render_to_response(
        'members/batch_add.html',
        {
        'form': form,
        },
    context_instance=RequestContext(request)
    )

The error I'm now getting when uploading is that 'initials_lower' does not exist, which implies that it's trying to create a new Group record, which I don't want it to do. I simply want it to use the pre-existing group chosen from the select and add that to it's groups many-to-many field.

我上传时遇到的错误是'initials_lower'不存在,这意味着它正在尝试创建一个新的Group记录,我不希望它这样做。我只是希望它使用从select中选择的预先存在的组,并将其添加到组的多对多字段。

Hope that makes sense, any help appreciated

希望有意义,任何帮助升值

1 个解决方案

#1


1  

Use get_or_create which creates an object only if it doesn't exist yet:

使用get_or_create只有在它不存在时才创建对象:

input_data.groups.get_or_create(initials=self.cleaned_data["group_name"]) 

#1


1  

Use get_or_create which creates an object only if it doesn't exist yet:

使用get_or_create只有在它不存在时才创建对象:

input_data.groups.get_or_create(initials=self.cleaned_data["group_name"])