nabil
nabil

Reputation: 29

Querying the images of an product in django

Can anyone help me to get just the images of an product?

I have these two models:

class Product(models.Model):
    name=models.CharField(max_length=200,null=True)
    price=models.DecimalField(max_digits=7,decimal_places=2)
    description=models.TextField(blank=True,null=True)
    image=models.ImageField(blank=True,null=True,default="images/default.jpg")
    size=models.ManyToManyField(Size)
    digital=models.BooleanField(default=False,null=True,blank=True)
    categories = models.ForeignKey(Category,on_delete=models.SET_NULL,blank=True, null=True) 
    objects = models.Manager() 

class Images(models.Model):
    product=models.ForeignKey(Product,on_delete=models.SET_NULL,null=True,blank=True)
    title=models.CharField(max_length=200,null=True,blank=True)
    image=models.ImageField(blank=True,null=True)

    def __str__(self):
        return str(self.title) if self.title else 'image'

and in my views.py I use this query to get the images of just a specific product but I get all the images of all the products

query = Images.objects.all().query
    query.group_by=['product']
    img=QuerySet(query=query)

Upvotes: 1

Views: 207

Answers (1)

willeM_ Van Onsem
willeM_ Van Onsem

Reputation: 476699

You can simply fetch the Product ojects of a single product with:

myproduct.images_set.all()

where myproduct is a Product object.

If you have only the primary key of the product, you can filter with:

Images.objects.filter(product_id=id_of_product)

Note: normally a Django model is given a singular name, so Image instead of Images.

Upvotes: 1

Related Questions