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

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
        product=mainproduct
        )

shop:view [works]

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

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)

>Solution :

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
    )
    # …
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