Assume that I have two models:
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)
What I wanna accomplish is creating a Product
object.
Assume I'll receive category_id
from the POST
request
>>> 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')
As you can see, there are two options, the first is to send category
instance to create()
method and the second is to send category_id
, so my question is which approach is better for performance?
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.
CodePudding user response:
If you have the primary key (category_id
) there is no need to fetch the category first, you thus can use:
Product.objects.create(category_id=category_id, title='Send only category id')
which will thus only make one query: a query to create the Product
, and thus will avoid querying for the category.
The two .create(…)
s will make exactly the same query since Django will simply retrieve the .id
of the category
object, and make the query with that 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.
No, if one would make a request with a category_id
for which there is no record for the table behind the Category
model, it will raise an IntegrityError
: the database will normally ensure that ForeignKey
s always point to valid items, so the Category.objects.get(id=category_id)
is not necessary: if you are only fetching it to fetch the category, you can omit that.