创建一个与另一个对象具有 ForeignKey 的对象
Create an object that has a ForeignKey with another object
假设我有两个模型:
class Category(models.Model):
title = models.CharField(max_length=255)
class Product(models.Model):
category = models.ForeignKey(Category, on_delete=models.CASCADE)
title = models.CharField(max_length=255)
我想要完成的是创建一个 Product
对象。
假设我将从 POST
请求
收到 category_id
>>> category = Category.objects.get(id=category_id)
>>> Product.objects.create(category=category, title='Send the category object')
>>> Product.objects.create(category_id=category_id, title='Send only category id')
如您所见,有两个选项,第一个是将 category
实例发送到 create()
方法,第二个是发送 category_id
,所以我的问题是哪个性能更好?
我知道我需要检查 category
是否存在于 DB
中,但这不是我在问题中谈论的情况。
如果你有主键(category_id
)不需要先获取类别,你可以使用:
Product.objects.create(<strong>category_id=category_id</strong>, title='Send only category id')
因此只会进行一次查询:创建 Product
的查询,从而避免查询类别。
这两个 .create(…)
将进行完全相同的查询,因为 Django 将简单地检索 category
对象的 .id
,并使用该 id
进行查询.
I know that I need to check if that category exists in the DB or not but this is not the case that I'm talking about in the question.
否,如果有人用 category_id
发出请求,而 Category
后面没有 table 的记录模型,它将引发一个 IntegrityError
:数据库通常会确保 ForeignKey
s 始终指向有效项目,因此 Category.objects.get(id=category_id)
不是 必需的: 如果你只是为了获取类别而获取它,你可以省略它。
假设我有两个模型:
class Category(models.Model):
title = models.CharField(max_length=255)
class Product(models.Model):
category = models.ForeignKey(Category, on_delete=models.CASCADE)
title = models.CharField(max_length=255)
我想要完成的是创建一个 Product
对象。
假设我将从 POST
请求
category_id
>>> category = Category.objects.get(id=category_id)
>>> Product.objects.create(category=category, title='Send the category object')
>>> Product.objects.create(category_id=category_id, title='Send only category id')
如您所见,有两个选项,第一个是将 category
实例发送到 create()
方法,第二个是发送 category_id
,所以我的问题是哪个性能更好?
我知道我需要检查 category
是否存在于 DB
中,但这不是我在问题中谈论的情况。
如果你有主键(category_id
)不需要先获取类别,你可以使用:
Product.objects.create(<strong>category_id=category_id</strong>, title='Send only category id')
因此只会进行一次查询:创建 Product
的查询,从而避免查询类别。
这两个 .create(…)
将进行完全相同的查询,因为 Django 将简单地检索 category
对象的 .id
,并使用该 id
进行查询.
I know that I need to check if that category exists in the DB or not but this is not the case that I'm talking about in the question.
否,如果有人用 category_id
发出请求,而 Category
后面没有 table 的记录模型,它将引发一个 IntegrityError
:数据库通常会确保 ForeignKey
s 始终指向有效项目,因此 Category.objects.get(id=category_id)
不是 必需的: 如果你只是为了获取类别而获取它,你可以省略它。