Filtering out a foreignkey model out of a foreignkey model


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

shop:view [works]

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


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/')


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


mainproduct is not a single 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(

Answered By – Willem Van Onsem

This Answer collected from stackoverflow, is licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0

Leave a Reply

(*) Required, Your email will not be published