postgresql 值错误:无法添加 *:实例在数据库“默认”上,值在数据库“无”上

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/7837033/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-20 23:22:59  来源:igfitidea点击:

ValueError: Cannot add *: instance is on database "default", value is on database "None"

djangopostgresql

提问by super9

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"

Models

楷模

  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])

Is it something to do with the fact that StockTemplate is an IKImage object?

这与 StockTemplate 是 IKImage 对象这一事实有关吗?

回答by diegueus9

The problem here is you need call the method save for both objects before add:

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

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

Django can not add a template of a plan if none of that objects don't have an id

如果没有一个对象没有 id,Django 无法添加计划模板