Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

is there a way to use something like p=product.objects.filter(category=home)?

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 :

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

image

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)
 

>Solution :

You can .filter(…) [Django-doc] with:

product.objects.filter(category__name='home')

Note: Models in Django are written in PascalCase, not snake_case,
so you might want to rename the model from product to Product.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading