I can set Category
with or without quotes to ForeignKey() as shown below:
class Category(models.Model):
name = models.CharField(max_length=50)
class Product(models.Model): # Here
category = models.ForeignKey("Category", on_delete=models.CASCADE)
name = models.CharField(max_length=50)
Or:
class Category(models.Model):
name = models.CharField(max_length=50)
class Product(models.Model): # Here
category = models.ForeignKey(Category, on_delete=models.CASCADE)
name = models.CharField(max_length=50)
And, I know that I can set Category
with quotes to ForeignKey()
before Category
class is defined as shown below:
class Product(models.Model): # Here
category = models.ForeignKey("Category", on_delete=models.CASCADE)
name = models.CharField(max_length=50)
class Category(models.Model):
name = models.CharField(max_length=50)
And, I know that I cannot set Category
without quotes to ForeignKey()
before Category
class is defined as shown below:
class Product(models.Model): # Error
category = models.ForeignKey(Category, on_delete=models.CASCADE)
name = models.CharField(max_length=50)
class Category(models.Model):
name = models.CharField(max_length=50)
Then, I got the error below:
NameError: name 'Category' is not defined
My questions:
What is the difference between the class name with or without quotes in a Django model field to have foreign key relationship?
Which should I use, the class name with or without quotes in a Django model field to have foreign key relationship?