CSV導入到具有多對多字段的模型

[英]CSV import to model with many-to-many field


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"]) 

注意!

本站翻译的文章,版权归属于本站,未经许可禁止转摘,转摘请注明本文地址:https://www.itdaan.com/blog/2012/02/25/72f091effbb29547c377ce45f1f5a510.html



 
粤ICP备14056181号  © 2014-2021 ITdaan.com