Praful Bagai
Praful Bagai

Reputation: 17362

Django - Foreign Key must be an instance

I've a model

from django.contrib.auth.models import User

class ModelA(models.Model):
    phone = models.CharField(max_length=20)
    user = models.ForeignKey(User)

I need to insert the data into this model. I've an endpoint hosted which provides me the following data {'phone':XXXXXXXX, 'user_id':123}.

Now when I insert the data into this model like

obj = ModelA.objects.create(phone=data['phone'], user = data['user_id]

It throws an error saying

Cannot assign "u'123'": "ModelA.user" must be a "User" instance.

Agreed, since because with django orm you can interact in terms of objects and not numbers. Hence I first found the object of the User and then created ModelA object.

user_obj = User.objects.get(id=data['id']
modelobj = ModelA.objects.create(phone=data['phone'], user = user_obj

Till here its all working fine.

Now, my question is that is there any other way of assigning/creating ModelA object directly using user_id not User object, since it first involves quering User Model and then inserting. Its like an extra read operation for every ModelA object created.

Upvotes: 15

Views: 17738

Answers (2)

lullis
lullis

Reputation: 304

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

Upvotes: 7

Vlad Lyga
Vlad Lyga

Reputation: 1143

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)

Upvotes: 17

Related Questions