Django - Foreign Key must be an instance

前端 未结 2 548
[愿得一人]
[愿得一人] 2021-01-11 16:59

I\'ve a model

from django.contrib.auth.models import User

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


        
相关标签:
2条回答
  • 2021-01-11 17:41

    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)
    
    0 讨论(0)
  • 2021-01-11 18:02

    (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)
    
    0 讨论(0)
提交回复
热议问题