Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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?

like image 954
super9 Avatar asked Oct 20 '11 13:10

super9


2 Answers

The problem here is that you need to call the method save for both objects before adding the template to the product:

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

Django can't add it if none of those objects has an id (plan and template)

like image 74
diegueus9 Avatar answered Sep 17 '22 19:09

diegueus9


One very common cause of this error is when you try to add the relations before saving the (parent) object. First, save the object and then add the relationships. Hopefully, it will be resolved.

Example:

a1 = Article(headline='Django lets you build Web apps easily') 

Now, if you directly try to add the relations like this:

a1.publications.add(p1) 

It will give an error.

Solution: SAVE IT first and then add relations!!

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

This will work flawlessly.

Docs

like image 32
Arghya Bhattacharya Avatar answered Sep 19 '22 19:09

Arghya Bhattacharya