我有三個模型,這里我展示兩個:
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)
例如,我怎樣才能進入由類別號 3 過濾的 views.py 檔案產品?我有這個: products_list = Product.objects.all()
提前致謝。
uj5u.com熱心網友回復:
您不需要在 Django 中為“第三個”表創建模型。您可以簡單地使用 ManyToManyField ,然后使用所需的條件過濾結果:
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
在 views.py 中,您必須過濾結果:
products_list = Product.objects.filter(categories__id=1)
轉載請註明出處,本文鏈接:https://www.uj5u.com/ruanti/389606.html
