我有一个自定义命令用JSON数据填充Django对象,这些数据主要以我想要的方式工作,但是我遇到了django-taggit字段的问题。解析完所有数据并以JSON格式输出后,类型在我的JSON对象中显示如下:
"genres": "latin pop, pop, singer-songwriter",
django-taggit采用以逗号分隔的标记列表,这就是它。但是当我运行下面的自定义命令时,我的模型的genres = TaggableManager()
字段中没有任何内容。
import json
import dateparser
from django.db import IntegrityError
from django.core.management.base import BaseCommand, CommandError
from concerts.models import Concert, Venue
class Command(BaseCommand):
help = "Load JSON concert data"
def add_arguments(self, parser):
parser.add_argument('concert_file', type=str)
def handle(self, *args, **options):
with open(options['concert_file']) as f:
data = json.load(f)
for concert in data:
try:
venue = Venue.objects.get(name=concert['venue'])
except Venue.DoesNotExist:
print "Can't find venue! " + concert['venue']
pass
del concert['venue']
try:
Concert.objects.create(venue=venue, **concert)
except IntegrityError:
print concert['slug'] + ": This concert already exists!"
pass
# if the slug unique contrainst fails, just pass this concert
如何让genres字段以我想要的方式填充?
答案 0 :(得分:0)
这是我想到的,以防其他任何人遇到这个问题:
class Command(BaseCommand):
help = "Load JSON concert data"
def add_arguments(self, parser):
parser.add_argument('concert_file', type=str)
def handle(self, *args, **options):
with open(options['concert_file']) as f:
data = json.load(f)
for concert in data:
try:
venue = Venue.objects.get(name=concert['venue'])
except Venue.DoesNotExist:
print "Can't find venue! " + concert['venue']
pass
del concert['venue']
try:
Concert.objects.create(venue=venue, **concert)
print concert['slug'] + ": Concert created!"
except IntegrityError: # if slug already exists
print concert['slug'] + ": This slug already exists!"
pass
# if the slug unique contrainst fails, just pass this concert
try:
new_concert = Concert.objects.get(slug=concert['slug'])
genres = concert['genres'].split(", ")
for genre in genres:
new_concert.genres.add(genre)
except KeyError or AttributeError: # if no genres key exists
pass
正如您所料,答案在于文档。我查看了django-taggit文档,特别是关于API的文档,然后在上面的上一个try / except语句中添加了标准标记。
此代码的奖励(对我来说)即使音乐会已经存在,此代码也会更新流派字段。