[英]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 


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

views.py (partial)

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

    return render_to_response(
        'form': form,

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.


Hope that makes sense, any help appreciated


1 个解决方案



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





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