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.