Home > Back-end >  Filtering out a foreignkey model out of a foreignkey model
Filtering out a foreignkey model out of a foreignkey model

Time:05-07

Tryna filter all productimg objects of MainProduct but getting ValueError Cannot use QuerySet for "MainProduct": Use a QuerySet for "Product". but can't use slug or id to filter it out of Product cuz it's homepage

home:view [doesnt work]

#can't use slug here
def home(request):
    mainproduct = MainProduct.objects.all()
    productimg = ProductImage.objects.filter(
        #wanna access all productimg objects of a single product i.e mainproduct
        product=mainproduct
        )

shop:view [works]

def detail_view(request, slug):
    products = Product.objects.get(slug=slug)
    productimg = ProductImage.objects.filter(product=products)

shop:model

class Product(models.Model):
    name = models.CharField(max_length=150)    

class ProductImage(models.Model):
    product = models.ForeignKey(Product, on_delete=models.CASCADE)
    image = models.ImageField(null=True, blank=True, upload_to='somewhere/')

home:model

class MainProduct(models.Model):
    product = models.ForeignKey(Product, on_delete=models.CASCADE)
    title = models.CharField(max_length=50)

CodePudding user response:

mainproduct is not a ingle product: it is a QuerySet of all MainProducts, even if there is a single MainProduct. If there is exactly one MainProduct, you query with .get(…) [Django-doc]:

def home(request):
    mainproduct = MainProduct.objects.get()
    productimg = ProductImage.objects.filter(
        product__mainproduct=mainproduct
    )
    # …
  • Related