ValueError:无法添加*:instance在数据库“default”上,value在数据库“None”上

时间:2011-10-20 13:56:41

标签: django postgresql

In [1]: from editor.models import *
In [4]: from subscriptions.models import *
In [5]: template = StockTemplate.objects.create(name='Template 1')
In [6]: template
Out[6]: <StockTemplate: Template 1>
In [7]: plan = SubscriptionPlan.objects.create(name='Bronze')
In [8]: plan
Out[8]: <SubscriptionPlan: Bronze>
In [12]: plan.templates.add(template)
---------------------------------------------------------------------------
ValueError                                Traceback (most recent call last)

/home/me/GitProjects/test_git/proj/<ipython console> in <module>()

/home/me/GitProjects/test_git/django-trunk/django/db/models/fields/related.pyc in add(self, *objs)
    498         if rel.through._meta.auto_created:
    499             def add(self, *objs):
--> 500                 self._add_items(self.source_field_name, self.target_field_name, *objs)
    501 
    502                 # If this is a symmetrical m2m relation to self, add the mirror entry in the m2m table


/home/me/GitProjects/test_git/django-trunk/django/db/models/fields/related.pyc in _add_items(self, source_field_name, target_field_name, *objs)
    558                         if not router.allow_relation(obj, self.instance):
    559                            raise ValueError('Cannot add "%r": instance is on database "%s", value is on database "%s"' %
--> 560                                                (obj, self.instance._state.db, obj._state.db))
    561                         new_ids.add(obj.pk)
    562                     elif isinstance(obj, Model):

ValueError: Cannot add "<StockTemplate: Template 1>": instance is on database "default", value is on database "None"

模型

  6 class SubscriptionPlan(models.Model):
  7     name = models.CharField(max_length=255)
  8     templates = models.ManyToManyField(StockTemplate)
  9     monthly_fee = models.IntegerField("Monthly Fee", max_length=16, default="0")
 10     modified = models.DateTimeField(auto_now=True, editable=False)
 11     created = models.DateTimeField(auto_now_add=True, editable=False)
 12 
 13     def __unicode__(self):
 14         return "%s" % self.name



 18 class StockTemplate(IKImage):
 19     name = models.TextField()
 20     description = models.TextField(blank=True)
 21 
 22     is_public = models.BooleanField(default=True)
 23 
 24     html = models.FileField(upload_to='stock_templates/html/', \
 25                             help_text='The file that will be used to render.')
 26     #css = models.FileField(upload_to='stock_templates/css/', blank=True)
 27 
 28     img = models.ImageField(upload_to='stock_templates/img/')
 29 
 30     modified = models.DateTimeField(auto_now=True)
 31     created = models.DateTimeField(auto_now_add=True)
 32 
 33     objects = StockTemplateManager()
 34 
 35     class IKOptions:
 36         spec_module = 'editor.specs'
 37         cache_dir = 'stock_templates/img/specs/'
 38         image_field = 'img'
 39 
 40     def __unicode__(self):
 41         return u"%s" % self.name
 42 
 43     def get_absolute_url(self):
 44         return reverse('preview_stock', args=[self.id])

是否与StockTemplate是一个IKImage对象有关?

2 个答案:

答案 0 :(得分:54)

这里的问题是你需要在添加之前调用两个对象的方法:

template.save()
plan.save()
plan.templates.add(template)

如果没有任何对象没有id

,Django无法添加计划的模板

答案 1 :(得分:0)

此错误的一个非常常见的原因是当您尝试在保存(父)对象之前添加关系时。首先保存对象,然后添加关系。希望能解决。

示例:

a1 = 文章(headline='Django 让您轻松构建网络应用')

现在,如果您直接尝试添加这样的关系:

a1.publications.add(p1)

这会出错。

解决办法:先保存再添加关系!!

a1.save() a1.publications.add(p1)

这将完美无缺。

文档:此处1