我正在尝试编写一个脚本,该脚本将从json文件填充数据库。看起来像这样:
class Command(BaseCommand):
def handle(self, *args, **options):
categories = load_from_json('categories')
ProductCategory.objects.all().delete()
for category in categories:
new_category = ProductCategory(**category)
new_category.save()
restaurants = load_from_json('restaurants')
Restaurant.objects.all().delete()
for restaurant in restaurants:
category_name = restaurant['category']
_category = ProductCategory.objects.get(name=category_name)
restaurant['category'] = _category
new_restaurant = Restaurant(**restaurant)
new_restaurant.save()
当我运行它时,django会引发一个错误:禁止直接分配给多对多集的正向。请改用category.set()。 我的模型如下:
class ProductCategory(models.Model):
name = models.CharField(verbose_name='наименование категории', max_length=64, unique=True)
image = models.ImageField(upload_to='category_images', blank=True)
description = models.TextField(verbose_name='описание категории', blank=True)
def __str__(self):
return self.name
class Restaurant(models.Model):
name = models.CharField(verbose_name='наименование ресторана', max_length=64, unique=True)
description = models.TextField(verbose_name='описание категории', blank=True)
image = models.ImageField(upload_to='restaurant_images', blank=True)
category = models.ManyToManyField(ProductCategory)
def __str__(self):
return self.name
看起来很多人都遇到了这个问题,但是我很难找到解决方法。