[Fixed]-Django – Foreign Key must be an instance

7πŸ‘

βœ…

(I keep getting votes for an answer that is wrong. If the database you are using has actual integrity checking, you can just use attr_name_id to insert the related object.

Wish I could just delete it. Look at the answer below.)

Basically, you can’t do that. Django’s ORM is expecting an object and not just a key. It’s the price to pay to have an extra layer of abstraction that is supposed to check for integrity at the application level, instead of the DB-level.

If performance is a problem (and in the general case it isn’t), you can make the read operation of the User object as light as possible. The only function will return a queryset of objects, forcing the select to retrieve only the id column, which is surely indexed.

user = User.objects.only('id').get(id=data['user_id'])
obj = ModelA.objects.create(phone=data['phone'], user=user)
πŸ‘€lullis

17πŸ‘

As can be seen in my historic comments, the accepted answer is not really correct.
So as @yekta requested I re-submit my comments:

To create the parent model, use integer value like:

ModelA.objects.create(phone=data['phone'], user_id=1)
πŸ‘€Vlad Lyga

Leave a comment