<p>在模型.py公司名称:</p>
<pre><code>class Compositions(models.Model):
composer_key = models.ForeignKey(
Composer,
)
composition = models.CharField(
max_length=383,
unique=False
)
date_created = models.DateTimeField(default=timezone.now)
class Meta(object):
unique_together = (('composer_key','composition'),)
</code></pre>
<p>这是我为上述模型编写的“动态”脚本,以便自动丢弃重复的条目。我已经将它保存到<code>./project_name/csv.py</code>,并在用数据填充文件<code>duc.csv</code>的相关列时从shell导入它。列不应包含标题。只有数据。在</p>
^{pr2}$
<p>在csv.py文件公司名称:</p>
<pre><code>from data.models import Composer, Compositions
import csv
import sys, traceback
from django.utils import timezone
filename = '/path/to/duc.csv'
with open(filename, newline='') as csvfile:
all_lines = csv.reader(csvfile, delimiter=',', quotechar='"')
for each_line in all_lines:
print (each_line)
try:
instance = Compositions(
id=None,
date_created=timezone.now(),
composer_key=Composer.objects.get(id=each_line[2]),
composition=each_line[3]
)
instance.save()
print ("Saved composition: {0}".format(each_line[3]))
except: // exception type must be inserted here
exc_type, exc_value, exc_traceback = sys.exc_info() //debugging mostly
print (exc_value)
</code></pre>