Using id (Primary Key) of a Model as ForeignKey when creating new model instances in Django through shell
Question: For illustration purposes, just two plain models:

    
    
    class PrimaryModel(models.Model):
        foo = models.CharField(max_length=50, unique=True)
    
    class SecondaryModel(models.Model):
        bar = models.ForeignKey(PrimaryModel)
    

Now trying to create instances in shell:

    
    
    >>> import testapp.models
    >>> a=testapp.models.PrimaryModel(foo="Test1")
    >>> a.save()
    >>> b=testapp.models.SecondaryModel(bar=1)
    

... and of course the error:

    
    
    Traceback (most recent call last):
      File "<console>", line 1, in <module>
      File "/home/pkaramol/Workspace/django-env/lib/python3.3/site-packages/django/db/models/base.py", line 405, in __init__
        setattr(self, field.name, rel_obj)
      File "/home/pkaramol/Workspace/django-env/lib/python3.3/site-packages/django/db/models/fields/related.py", line 337, in __set__
        self.field.name, self.field.rel.to._meta.object_name))
    ValueError: Cannot assign "1": "SecondaryModel.bar" must be a "PrimaryModel" instance.
    

The question is why can't we use the id of the PrimaryModel (as in the
erroneous example above) and we have to use an instance? Have also tried to
use the `to_field` field as in

    
    
    class SecondaryModel(models.Model):
        bar = models.ForeignKey(PrimaryModel, to_field='foo')
    

but that did not change the situation.


Answer: If you want to use id of a PrimaryModel you should do it like this:

    
    
    b=testapp.models.SecondaryModel(bar_id=1)
    

