【发布时间】:2019-11-21 02:40:57
【问题描述】:
我正在尝试导入一个包含多对多关系的 JSON 文件,但遇到了一些问题。这是我的代码:
book.json
{
"title": "The Lord of the Rings",
"categories": [
"Fantasy",
"Action",
"Adventure"
]
}
models.py
from django.db import models
class Category(models.Model):
guid = models.CharField(max_length=36)
display_name = models.CharField(max_length=50)
description = models.TextField()
def __str__(self):
return self.display_name
class Book(models.Model):
title = models.CharField(max_length=200)
categories = models.ManyToManyField(Category)
def __str__(self):
return self.title
resources.py
from import_export import resources
from import_export.fields import Field
from import_export.widgets import ManyToManyWidget
from .models import Book, Category
class BookResource(resources.ModelResource):
categories = Field(widget=ManyToManyWidget(Category))
class Meta:
model = Book
import_id_fields = ('title',)
importer.py
from resources import BookResource
from models import Book
with open("book.json", 'r') as f:
book = '[' + f.read() + ']'
result = BookResource().import_data(tablib.Dataset().load(book), raise_errors=True, dry_run=True)
这似乎没有错误地运行,并将新的book 添加到数据库中。问题是它不会在book_categories 表(PostgreSQL)中创建新条目。我想我肯定在某处遗漏了一步,因为我还没有定义如何找到正确的category 数据库条目,给定display_name 字符串列表。我在正确的轨道上吗?
【问题讨论】:
-
好吧,您在 importer.py 中的导入不正确,但我想这是一个复制问题。
标签: python django postgresql django-models django-import-export