Django-外键必须是实例 [英] Django - Foreign Key must be an instance

查看:56
本文介绍了Django-外键必须是实例的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个模型

from django.contrib.auth.models import User

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

我需要将数据插入此模型。我托管了一个端点,可为我提供以下数据 {'phone':XXXXXXXX,'user_id':123}

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]

抛出错误说

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

同意,因为使用django orm可以在对象而不是数字上进行交互,因此我首先找到了User的对象,然后创建的ModelA对象。

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

此处一切正常。

现在,我的问题是还有其他方法可以直接分配/创建 ModelA 对象使用 user_id 而不使用r 对象,因为它首先涉及到查询用户模型然后进行插入。就像对每个创建的ModelA对象进行额外的读取操作一样。

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.

推荐答案

(我不断为错误的答案投票。如果您正在使用的数据库具有实际的完整性检查,您可以使用 attr_name _id插入相关对象。

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

基本上,您不能这样做。 Django的ORM需要一个对象,而不仅仅是一个键。

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.

如果性能很差,那么应该付出额外的抽象层,这应该在应用程序级别而不是数据库级别检查完整性,这是必须付出的代价。问题(通常不是),您可以使User对象的读取操作尽可能轻。 only 函数将返回对象的查询集,强制select仅检索ID列,该列肯定已索引。

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)

这篇关于Django-外键必须是实例的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆