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.
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)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With