Aditya Singh
Aditya Singh

Reputation: 970

Unable to get distinct results for queryset

here is models.py

class Product(models.Model):

    brand = models.ForeignKey(Brand , related_name='products')
        category = models.ForeignKey('Category', verbose_name='categories', related_name='products' , default='')
        parent = models.ForeignKey('self' , related_name = 'children' , null=True , blank=True)
        title = models.CharField(max_length=500)

class StoreProduct(models.Model):
        product = models.ForeignKey('products.Product')
        category = models.ForeignKey('products.Category')
        store = models.ForeignKey('Store')

class Store(models.Model):
    user = models.ForeignKey(settings.AUTH_USER_MODEL , null=True , blank=True)
    StoreName = models.CharField(max_length=50 , default = '')
    items = models.ManyToManyField('products.Product', through=StoreProduct)
    brand = models.ForeignKey('products.Brand' , null=True , blank=True)
    City = models.CharField(max_length=50 , default = '')
    Area = models.CharField(max_length=50 , default = '')
    Address = models.TextField(max_length=500)
    MallName = models.CharField(max_length=50 , null=True , blank=True)
    slug = models.SlugField(blank=True ,unique=True)

here is views.py

queryset = StoreProduct.objects.all().distinct()

Multiple store can contain the same product and but they should appear once on the product grid page.
Distinct query is not working.
What can i do to show distinct values in the above case?
Thanks in Advance

Upvotes: 0

Views: 56

Answers (1)

Dhia
Dhia

Reputation: 10609

If you are using PostgreSQL, specify the level of distinction:

queryset = StoreProduct.objects.distinct('product')

you can also use it in conjunction with values(), order_by(), etc:

queryset = StoreProduct.objects.values('product').distinct()

I will suggest the following as solution but not the solution; either you choose PosgreSQL as database, specially that the newest Django version is coming with more built-in support for complex data structure, or you try make you own filter as follow (but in case you have large dataset this will be really bad):

store_product_id_list = StoreProduct.objects.values('product').distinct()
store_product_list = []
for obj in store_product_id_list:
    store_product_obj = StoreProduct.objects.filter(product_id=obj.get('product')).first()
    store_product_list.append(store_product_obj)

Check distinct for more examples

Upvotes: 1

Related Questions