Home > database >  Filtering in a many-to-many relationship in Django
Filtering in a many-to-many relationship in Django

Time:12-22

I have three models, here I show two:

class Product(models.Model):
    description = models.CharField(max_length=50)
    price = models.IntegerField()
    stock = models.IntegerField()
    def __str__(self):
        return self.description

# Many-to-many relations
class ProductsCategories(models.Model):
    idProduct = models.ForeignKey(Product, on_delete=CASCADE)
    idCategory = models.ForeignKey(Category, on_delete=CASCADE)

How can I get in the views.py file products filtered by the category number 3 for instance? I have this: products_list = Product.objects.all()

Thanks in advance.

CodePudding user response:

You don't need to create a model to the "third" table, in Django. You can simply use a ManyToManyField and next filter the results with the desired criteria:

class Product(models.Model):
    description = models.CharField(max_length=50)
    price = models.IntegerField()
    stock = models.IntegerField()

    categories = models.ManyToManyField(Category)

    def __str__(self):
        return self.description

In views.py you have to filter the results:

products_list = Product.objects.filter(categories__id=1)
  • Related