Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 559
PythonEnthusiast Avatar asked May 03 '15 17:05

PythonEnthusiast


1 Answers

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)
like image 108
Vlad Lyga Avatar answered Sep 21 '22 03:09

Vlad Lyga