There are many related questions on SO about this topic, but they all seem to deal with cases where the element being assigned is actually the instance.id or a string with the instance name.
I have two models, one called Photo, the other called Material.
class Photo(models.Model):
mat = models.ForeignKey(
Material, related_name='photos',null=True, blank=True)
In the shell, I get a Photo object, and I create a Material object.
[in : 1]p = Photo.objects.all()[0] # get the first
[in : 2]m, bool = Material.objects.get_or_create(id=1) # get_or_create returns a tuple, take the first
[in : 3]p
[out:1] <Photo: Photo object>
[in : 4]m
[out:2] <Material:Material object>
[in : 5]p.mat = m
---------------------------------------------------------------------------
ValueError Traceback (most recent call last)
<ipython-input-60-836d23304359> in <module>()
----> 1 p.mat = m
/home/rootadmin/opensurfaces/venv/local/lib/python2.7/site-packages/django/db/models/fields/related.pyc in __set__(self, instance, value)
595 instance._meta.object_name,
596 self.field.name,
--> 597 self.field.rel.to._meta.object_name,
598 )
599 )
ValueError: Cannot assign "<Material: Material object>": "Photo.mat" must be a "Material" instance.
As far as I can tell, m is a Material instance. What is going wrong?