I have some categories that I can filter them by primary key like this :
p=product.objects.filter(category=2)
but I do not want to bother my self with primary keys I want to filter with exact name of the category not primary key.
I have categories like this :
is there a way to use something like p=product.objects.filter(category=home)
?
models:
class category(models.Model):
name=models.CharField(max_length=255, db_index=True)
def __str__(self):
return self.name
class product(models.Model):
category = models.ForeignKey(category, related_name='products',on_delete=models.CASCADE)
image=models.CharField(max_length=500)
description=models.CharField(max_length=500)
price=models.CharField(max_length=50)
buy=models.CharField(max_length=100)
CodePudding user response:
You can .filter(…)
[Django-doc] with:
product.objects.filter(category__name='home')
Note: Models in Django are written in PascalCase, not smallcase, so you might want to rename the model from
toproduct
Product
.