Django object unique id value in Template

in this modal I have a foreign Key Named stockCode That key has duplicated values and I want to get only one of them(unique).

class Product(models.Model):
   stockCode = models.CharField(primary_key=True,max_length=50,null=False, blank=False)
   Name = models.CharField(max_length=120,null=False, blank=False)
   Desc = models.CharField(max_length=120,null=True, blank=True)
   price1 = models.FloatField(null=False, blank=False)
   price2 = models.FloatField(null=False, blank=False)
   publish = models.BooleanField(default=True)

   def __str__(self):
       return str(self.stockCode)

class Stock(models.Model):
    id = models.AutoField(primary_key=True)
    productId = models.ForeignKey(Product,null=False, blank=False,on_delete=models.PROTECT)
    sizeId = models.ForeignKey(Varyasyon,null=True, blank=True,on_delete=models.PROTECT)
    colorId = models.ForeignKey(Renk,null=False, blank=False,on_delete=models.PROTECT)
    grubId = models.ForeignKey(Grub,null=True, blank=True,on_delete=models.PROTECT)
    stock = models.IntegerField(null=True, blank=True)
    photo = models.ImageField(null=False, blank=False)
    def __str__(self):
        return str(self.grubId)
    

I've tried this:

@xframe_options_sameorigin
def product(request):
    stock = Stock.objects.all().values('productId').distinct()
    return render(request,"product.html",{"products":stock})

but it gives me only the id value ant tried to add .values('productId','productId__Name') it gives me productId__Name unique value and I don't want this. I want only productId to be unique.


Solution 1:

If you're using a Postgres database, you can pass column names to the distinct function to tell Postgres which columns to check for distinctness. Otherwise the database will use the entire row to check for distinctness. See the documentation for distinct here.

In your case:

stock = Stock.objects.all().values('productId__stockCode').distinct('productId__stockCode')

PS. I'd recommend to follow the Django naming conventions because it will make your code easier to understand and use:

  1. productId should rather be product because the ForeignKey references a Product. Django will create a product_id column in a migration.
  2. Name should be lowercase name.
  3. stockCode should be stock_code.